Solutions for efficient backend - frontend cooperation in Django projects.
AJAX RequestsMaking AJAX requests with jQuery is very easy. For this example I created a main page template:
This covers all the elements. The request should now work and you can check it in Firebug or other browser developers console. The request should return "ok" from the view.
This simple code makes a GET request. Quite often POST requests are needed - like when some data is sent. jQuery part is very easy:
In "AjaxView" we change "get" to "post" and reload the page. The AJAX request should fail - 403, "CSRF verification failed. Request aborted.". We made a POST request without the csrf token (what we put in forms). You could use csrf_exempt on the view but that isn't the best solution for this problem.
In csrf Django documentation we can find a solution. We have to set X-CSRFToken header with the csrf cookie value. Using jQuery Cookie it will be easy:Using beforeSend we can set the X-CSRFToken token. It's almost done. If your browser has the "csrftoken" cookie the request will work, but if it's not there it will still fail. Django won't make the cookie if it's not needed. To ensure cookie existence add 'django.views.decorators.csrf._EnsureCsrfCookie', to MIDDLEWARE_CLASSES.
We have a fully working AJAX request. Now it's time to use JSON to get a batch of data from the view.Just import "json" module and modify the view to: That will work, but we can do it even better.
django-annoying is a set of decorators and helpers shortening some common tasks. We can use the ajax_request decorator to improve our view. If we use this decorator on a view it has to return a dictionary. The decorator will encode it to JSON and will return a JsonResponse (like HttpResponse but with correct JSON mimetype).We can instal django-annoying the usuall way: