Processing AJAX request in Django
I want to send several asynchronous requests from my web application's frontend to Django backend. I am going to do this using jQuery. But how exactly I need to process AJAX requests in Django?
I want to send several asynchronous requests from my web application's frontend to Django backend. I am going to do this using jQuery. But how exactly I need to process AJAX requests in Django?
First of all, you need to create a path in your urls.py file. This could be a normal path, the same as other paths in your application. Next, create a view that will process the request and returns the response in the JSON form. This could be "django.http.JsonResponse" object. Inside "JsonResponse" place the dictionary with the response (any data you want to send to the frontend or the message and error details). That's all on the back-end. All other things (process the response, update the page, etc.) you should do on the front-end.
If you want this endpoint to be accessible only for AJAX requests (not for regular), you can write the following condition at the beginning of the view:
if not request.is_ajax():
return HttpResponseNotFound("Page not found")
So, if somebody will try to enter the URL for this path in the browser (instead of sending asynchronous request), he/she will get the "Page not found" response.
Thanks guys, it was helpful.
Just drop us an email to ...
Show more