Where's My JSON Data in My Incoming Django Request

Where's my JSON data in my incoming Django request?

If you are posting JSON to Django, I think you want request.body (request.raw_post_data on Django < 1.4). This will give you the raw JSON data sent via the post. From there you can process it further.

Here is an example using JavaScript, jQuery, jquery-json and Django.

JavaScript:

var myEvent = {id: calEvent.id, start: calEvent.start, end: calEvent.end,
allDay: calEvent.allDay };
$.ajax({
url: '/event/save-json/',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: $.toJSON(myEvent),
dataType: 'text',
success: function(result) {
alert(result.Result);
}
});

Django:

def save_events_json(request):
if request.is_ajax():
if request.method == 'POST':
print 'Raw Data: "%s"' % request.body
return HttpResponse("OK")

Django < 1.4:

  def save_events_json(request):
if request.is_ajax():
if request.method == 'POST':
print 'Raw Data: "%s"' % request.raw_post_data
return HttpResponse("OK")

Getting a JSON request in a view (using Django)

This is how I did it:

def api_response(request):
try:
data=json.loads(request.raw_post_data)
label=data['label']
url=data['url']
print label, url
except:
print 'nope'
return HttpResponse('')

How to receive json data using HTTP POST request in Django 1.6?

You're confusing form-encoded and JSON data here. request.POST['foo'] is for form-encoded data. You are posting raw JSON, so you should use request.body.

received_json_data=json.loads(request.body)

Django json post request parse

Data to be sent as json must be "stringified", so you need to do "JSON.stringify(data)"

$.ajax({
type:"POST",
url:"{% url 'validate_purchase' %}",
data: JSON.stringify(data),
dataType: "application/json; charset=UTF-8",
success: function(data){
}
});

Is transferring JSON data in Django possible without JS / JQuery?

In Django's views you usually pass such values as context.

function based view:

def a_view(request):
context = {
'some_things': Thing.objects.all()
}
return render(request, 'your_template.html', context)

class based view:

class TheView(View):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['some_things'] = Thing.objects.all()
return context

With any of given approaches in template it will work like this:

{% for thing in some_things %}
{{ thing }}, {{ thing.id }}, {{ thing.get_related_things }}
{% endfor %}


Related Topics



Leave a reply



Submit