KenanBek
KenanBek

Reputation: 1067

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.

Upvotes: 4

Views: 3450

Answers (2)

dhana
dhana

Reputation: 6525

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)    

       }
});

Upvotes: 2

Thomas Orozco
Thomas Orozco

Reputation: 55199

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

Upvotes: 5

Related Questions