2

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?

2
  • 1
    Have you tried posting the CSRF token as well? Commented 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. Commented Apr 12, 2012 at 20:14

2 Answers 2

4

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/

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Then decorate your view with csrf_exempt
2

Use the @csrf_exempt decorator on any API views.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.