What is the proper way to post json to Django? I have tried to use views, but I am not certain how to handle csrf. Is there another way to bypass views and simply accept a post of json?
-
1Have you tried posting the CSRF token as well?Ignacio Vazquez-Abrams– Ignacio Vazquez-Abrams2012-04-12 17:53:32 +00:00Commented Apr 12, 2012 at 17:53
-
I should have been more clear - this post is not happening from ajax or a form of any sort. This is more for a web api without any authorization. I need to be able to allow an anonymous user to post a json msg to Django and reply back with json.ewhitt– ewhitt2012-04-12 20:14:41 +00:00Commented Apr 12, 2012 at 20:14
2 Answers
Views are what handle the post data. There is no concept of "bypass views" because that is where the work of processing a request is done.
This is probably what your are looking for: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
This shows you how to handle csrf tokens with ajax (namely by using cookies).
I also might suggest you slow down and try to work through the tutorial found here: https://docs.djangoproject.com/en/dev/intro/tutorial01/
You will likely have an easier time with django if you undertstand how the pieces (Models, Views, Templates, urls, Forms, etc) fit together.
Since you've added that these are API calls the simplest thing to do would be to mark these views as csrf_exempt. Additionally, as you might guess creating an API from models is a common task (I'm assuming that your API maps to models as that's the common case and you haven't specified) you may want to not reinvent the wheel and instead use piston or tastypie to make this easier on you: http://djangopackages.com/grids/g/api/