Create Ajax View method for GET/POST in Django

Suppose if you want to get some data from Django server. You will usually get the data in the template via a View method. Hitting the URL will also cause the page to refresh.

What if you simply wanted some data without page refresh?

You can make an Ajax call to a method that returns data as JSON. It will get the the data without refreshing the page.

Follow the below steps to make an Ajax call to a Django Application URL.

It can be done in two steps.

Step 1: Create a View function that returns data as JSON.

In the return statement instead of request.POST you can pass the data that you want to return.

postData is the data sent via the Ajax request in front-end.

from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse

@csrf_exempt
def ajaxFunction(request):
      #if request.method == "GET":
		#perform operation with get request

	if request.method == "POST":
		#perform operation with post data
		#print(request.POST.get("postData","failed"))

		return JsonResponse(request.POST, safe=False)

Step 2: Create a URL pattern that maps to the above created function.

    url(r'^ajax-url/', 'app.views.ajaxFunction', name='ajaxUrl'),

Now finally, call the URL using any front-end client or Postman application.

Leave a Reply

Your email address will not be published.