Reputation: 13178
I'm trying to create a web service in Django. For some reason it is working in a GET request but not as a POST (which is my requirement). I have the below url:
url(r'^rest/user/(.*)/(.*)/$', 'rest.views.user.user')
So if the user was to send a message to /rest/user/ANY_CHARACTER/ANY_CHARACTER/
, it will go to the below function:
def user(request, string1, string2):
if request.method == "POST":
return HttpResponse(string1 + ' ' + string2)
else:
return HttpResponse('error')
Everytime I send a GET request, i'm getting error
(which is correct), but everytime I send the same URL as POST, i'm getting HTTP 500 error. Is there something i'm missing here?
EDIT
The error log in the terminal has the following:
[02/Jul/2012 19:13:57] "POST /rest/user/hi/hi HTTP/1.1" 500 61994
However, when I send the same command as GET, I'm not getting any errors...which is very strange.
EDIT 1
I'm noticing the below error when I send a POST request, it works on all other types:
<p>Reason given for failure:</p>
<pre>
CSRF token missing or incorrect.
</pre>
<p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when
<a href='http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ref-contrib-csrf'>Django's
CSRF mechanism</a> has not been used correctly. For POST forms, you need to
ensure:</p>
My question is...how do I handle this for webservice requests? Sorry, tried searching for this, but is there a way to get around CSRF for RESTful webservice requests?
Upvotes: 1
Views: 1189
Reputation: 13178
You can do it like this:
from django.views.decorators.csrf import csrf_exempt, csrf_protect
@csrf_exempt
def user(request, string1, string2):
if request.method == "POST":
return HttpResponse(string1 + ' ' + string2)
else:
return HttpResponse('error')
I should add that csrf_exempt
is probably not safe...but will work.
Upvotes: 2