jquery - internal server eroor 500 django when using simplejson.loads(request.raw_post_data) -
i'm trying receive json object jquery client when call simplejson.loads(request.raw_post_data) internal server error 500. server receives call since i'm getting callback fro server when simplejson.loads(request.raw_post_data) line commented. uncomment line error thrown.
ajaxtest.html
<!doctype html> <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#post").click(function(){ var test = new object(); test.name = "kalle"; test.pw = "kula"; $.ajax({ url: "ajaxtest/", type: 'post', datatype: 'json', data: {client_response: json.stringify(test), csrfmiddlewaretoken: '{{ csrf_token}}'}, success: function(result) { alert(result); } }); }); }); </script>
views.py
from django.shortcuts import render django.shortcuts import render_to_response django.template import requestcontext django.http import httpresponse django.utils import simplejson manges.models import user # create views here. def ajax_test(request): print 'hej' if request.method == 'get': print 'get' c = user.objects.get(pk=1) print c.emailadress print c.password return httpresponse(simplejson.dumps(c, default=user.serializable)) if request.method == 'post': print 'post' data = simplejson.load(request.raw_post_data) print json_data.name return httpresponse(simplejson.dumps('got json!')) def start_page(request): print 'start' return render_to_response('ajaxtest.html', context_instance=requestcontext(request))
urls.py
from django.conf.urls import patterns, include, url manges.views import ajax_test, start_page django.contrib import admin admin.autodiscover() urlpatterns = patterns('manges.views', url(r'^$', start_page), url(r'^ajaxtest/$', ajax_test), # examples: # url(r'^$', 'myforum.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), )
any ideas??
raw_post_data doesn't contain json, why conversion throwing.
when send request, passed data
{client_response: json.stringify(test), csrfmiddlewaretoken: '{{ csrf_token}}'}
jquery serializes object in post parameters. see page jquery.ajax.
so on server side, httprequest.raw_post_data doesn't have json directly. extract json, need use post parameter contains json, accessible through
request.post["client_response"]
Comments
Post a Comment