how to return json dictionary in django ajax update

  • Last Update :
  • Techknowledgy :

You'll need to export your object list to a JSON dictionary.

if request.path == "/sort/":
   sortid = request.POST.get('sortid')
locs = Location.objects.order_by(sortid)
if request.is_ajax():
   import json
return HttpResponse(json.dumps(locs), mimetype = "application/json")

A cheap example, here's my object_list.html:

<ul id='object-list'>
    {% for object in object_list %}
        <li>{{ object.value }}</li>
    {% endfor %}
</ul>

And here's my base.html:

<html>
<title>Example</title>
    <body>
        {% include 'object_list.html' %}
    </body>
</html>

If you are trying to populate the value in ajax function first you need to convert the queryset object into the json object like

if request.path == "/sort/":
   sortid = request.POST.get('sortid')
locs = Location.objects.order_by(sortid)
if request.is_ajax():
   locs = json.dumps(locs)
return HttpResponse(locs, mimetype = "application/json")

Suggestion : 2

A better way is to use Django's render_to_response shortcut. You don't actually "need" to respond with JSON. You can just respond to the request with a string.,How do I add more than one dictionary list to a Django return render call?,If you are trying to populate the value in ajax function first you need to convert the queryset object into the json object like ,This let's the view get called normally, via a standard GET, or via an XHTTP request, returning only the partial HTML you want to update. Handy!

You'll need to export your object list to a JSON dictionary.

if request.path == "/sort/":
   sortid = request.POST.get('sortid')
locs = Location.objects.order_by(sortid)
if request.is_ajax():
   import json
return HttpResponse(json.dumps(locs), mimetype = "application/json")

A cheap example, here's my object_list.html:

<ul id='object-list'>
    {% for object in object_list %}
        <li>{{ object.value }}</li>
    {% endfor %}
</ul>

And here's my base.html:

<html>
<title>Example</title>
    <body>
        {% include 'object_list.html' %}
    </body>
</html>

If you are trying to populate the value in ajax function first you need to convert the queryset object into the json object like

if request.path == "/sort/":
   sortid = request.POST.get('sortid')
locs = Location.objects.order_by(sortid)
if request.is_ajax():
   locs = json.dumps(locs)
return HttpResponse(locs, mimetype = "application/json")

Suggestion : 3

A GET request with fetch is made by supplying it the URL of the view and the appropriate headers. Once the request is made and the view returns the requested data, the response then needs to be converted to JSON before it is made available for further actions.,We need a view to handle the AJAX request from the fetch call. This can be done in multiple ways, but one of the simplest is to use a function-based view that takes the request and returns a JsonResponse with the requested data.,To prevent this from happening, we can add a check in the view to make sure the request is an AJAX request by using the request.is_ajax() method.,The view that accepts the POST request will get the data from the request, perform some operation with it, and return a response.

A GET request with fetch is made by supplying it the URL of the view and the appropriate headers. Once the request is made and the view returns the requested data, the response then needs to be converted to JSON before it is made available for further actions.

fetch(URL, {
      headers: {
         'Accept': 'application/json',
         'X-Requested-With': 'XMLHttpRequest', //Necessary to work with request.is_ajax()
      },
   })
   .then(response => {
      return response.json() //Convert response to JSON
   })
   .then(data => {
      //Perform actions with the response data from the view
   })

We need a view to handle the AJAX request from the fetch call. This can be done in multiple ways, but one of the simplest is to use a function-based view that takes the request and returns a JsonResponse with the requested data.

# views.py
from django.http
import JsonResponse

def ajax_get_view(request): # May include more arguments depending on URL parameters
# Get data from the database - Ex.Model.object.get(...)
data = {
   'my_data': data_to_display
}
return JsonResponse(data)

POST requests with fetch require more parameters than GET requests.

fetch(URL, {
      method: 'POST',
      credentials: 'same-origin',
      headers: {
         'Accept': 'application/json',
         'X-Requested-With': 'XMLHttpRequest', //Necessary to work with request.is_ajax()
         'X-CSRFToken': csrftoken,
      },
      body: JSON.stringify({
         'post_data': 'Data to post'
      }) //JavaScript object of data to POST
   })
   .then(response => {
      return response.json() //Convert response to JSON
   })
   .then(data => {
      //Perform actions with the response data from the view
   })

The view that accepts the POST request will get the data from the request, perform some operation with it, and return a response.

# views.py
from django.http
import JsonResponse
import json

def ajax_post_view(request):
   data_from_post = json.load(request)['post_data'] #Get data from POST request
#Do something with the data from the POST request
#If sending data back to the view, create the data dictionary
data = {
   'my_data': data_to_display,
}
return JsonResponse(data)

To prevent this from happening, we can add a check in the view to make sure the request is an AJAX request by using the request.is_ajax() method.

# views.py
from django.http
import JsonResponse

def ajax_view(request):
   if request.is_ajax():
   data = {
      'my_data': data_to_display
   }
return JsonResponse(data)

Suggestion : 4

by Brian | Oct 30, 2020 | Django | 6 comments

Inside our views.py file, add the following code:

def ajax_view(request):
   data = {
      "msg": "It worked!!",
   }
return JsonResponse(data)

Now that we have our ajax_view setup, let’s wire it up to our urls.py.

from django.contrib
import admin
from django.urls
import path
from.views
import ajax_view

urlpatterns = [
   path('admin/', admin.site.urls),
   path('ajax/', ajax_view, name = "ajax"),
]

Let’s start with vanilla JavaScript and use the Fetch API to make an AJAX GET request to our ajax endpoint.

  fetch('/ajax/')
     .then(function(response) {
        return response.json();
     })
     .then(function(data) {
        console.log(data);
     })
     .catch(function(err) {
        console.log(err);
     })

To handle both POST and GET requests with our AJAX view, we can use an if statement and filter the requests by their methods. Add the following code to your AJAX view.

def ajax_view(request):
   if request.method == "POST":
   print(request.POST)
data = {
   "msg": "Data has been POSTED!",
}
return JsonResponse(data)
else:
   data = {
      "msg": "It worked!!",
   }
return JsonResponse(data)

Django provides a JavaScript function that gets the CSRF token for us. We will use this function to get our CSRF token to send in our POST request.

    function getCookie(name) {
       let cookieValue = null;
       if (document.cookie && document.cookie !== '') {
          const cookies = document.cookie.split(';');
          for (let i = 0; i < cookies.length; i++) {
             const cookie = cookies[i].trim();
             // Does this cookie string begin with the name we want?
             if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
             }
          }
       }
       return cookieValue;
    }
    const csrftoken = getCookie('csrftoken');

Suggestion : 5

Since key1 is a JSON object, we need to convert it(not the whole data) to JSON string before sending using ajax.,When we send simple key, value pairs in the javascript object, we can simply generate the JSON object like this:,We need to convert this JSON string to dictionary in Python.,I use the below javascript code when sending ajax requests

// Javascript Code
data = {
   'key1': 'value1',
   'key2': 'value2'
}
# Django Code
print request.POST['key1'] # prints value1
if value1 is not array
 // Javascript Code
 data = {
    "key1": [1, 2, 3],
    "key2": "simple string"
 }
# Python Code
key1 = request.POST.getlist("key1[]") #Dont forget[].It returns the list[1, 2, 3]
key2 = request.POST['key2'] #Simple strings can be accessed normally
// Javascript Code
data = {
   "key1": {
      "a": "b"
   }, //It can be as deep/complex as you want. Dictionary in a dictionary in python. JSON object in JSON object in javascript.
   "key2": [1, 2, 3], //Some list
   "key3": "simple string"
}
// Javascript Code
data['key1'] = JSON.stringify(data['key1'])