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.
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
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)
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With