Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a best practice to receive JSON input in Django views?

I am trying to receive JSON in Django's view as a REST service. I know there are pretty developed libraries for REST (such as Django REST Framework). But I need to use Python/Django's default libraries.

like image 958
KenanBek Avatar asked Mar 20 '23 18:03

KenanBek


2 Answers

request.POST is pre processed by django, so what you want is request.body. Use a JSON parser to parse it.

import json

def do_stuff(request):
  if request.method == 'POST':
    json_data = json.loads(request.body)
    # do your thing
like image 155
Thomas Orozco Avatar answered Mar 23 '23 20:03

Thomas Orozco


Send the response to browser using HttpResponse without page refreshing.

views.py

from django.shortcuts import render, HttpResponse,

import simplejson as json

def json_rest(request):
   if request.method == "POST":
      return HttpResponse(json.dumps({'success':True, 'error': 'You need to login First'}))
   else:
      return render(request,'index.html')

urls.py

(r^'/','app.views.json_rest')

client side:

$.ajax({
     type:"post",
     url: "/",
     dataType: 'json',
     success: function(result) {
         console.log(result)    

       }
});
like image 37
dhana Avatar answered Mar 23 '23 20:03

dhana