Processing AJAX request in Django

sArmzeam11 report abuse

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?

Answers

uxdyx report abuse

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.

Finchpal report abuse

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.

sArmzeam11 report abuse

Thanks guys, it was helpful.

Add Answer

Need support?

Just drop us an email to ... Show more