Ajax views with django

I am working on a rather large project right now, where each view should be accessible through a regular request and ajax request through the same URL. I am looking for ideas on how to create a small structure to handle this very versatile way. Depending on whether the view is called via ajax or not, it needs to display a different template and return json instead of the object HttpResponse. I would like to collect any ideas on this topic - the main goal should not be to avoid the dry principle and create code that can be used as many times as possible. I have already considered different options as general representations, decorators on representations, etc., but I am open for anything. So please, let me hear your suggestions or point me to any ready-made snippets that you know!

+3
source share
2 answers

This article seems like a pretty good guide to working with ajax and regular requests. The object requesthas a method is_ajax()that will search HTTP_X_REQUESTED_WITH: XMLHttpRequest. This, of course, will depend on how correctly these values ​​are set when sending a javascript request.

From the article:

from django.http import HttpResponse
from django.core import serializers
from django.shortcuts import render_to_response
from your_app.models import ExampleModel

def xhr_test(request, format):
    obj = ExampleModel.objects.all()
    if request.is_ajax():
        data = serializers.serialize('json', obj)
        return HttpResponse(data,'json')
    else:
        return render_to_response('template.html', {'obj':obj}, context=...)

django-piston, RESTful Django. . ( ), mime- , URL-, html, xml, json. , , ( ) .

+6

. , .

Ajax , , JSON.

0

Source: https://habr.com/ru/post/1786500/


All Articles