Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django POST URL error

I am trying to make a REST Api in Django by outputting Json. I am having problems if i make a POST request using curl in terminal. The error i get is

You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/add/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.

My url.py is

    from django.conf.urls.defaults import patterns, include, url import search  # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover()  urlpatterns = patterns('',      url(r'^query/$', 'search.views.query'),     url(r'^add/$','search.views.add'), ) 

and my views are

# Create your views here. from django.http import HttpResponse from django.template import Context,loader import memcache import json  def query(request):     data=['a','b']      mc=memcache.Client(['127.0.0.1:11221'],debug=0)     mc.set("d",data);      val=mc.get("d")      return HttpResponse("MEMCACHE: %s<br/>ORIGINAL: %s" % (json.dumps(val),json.dumps(data)) )  def add(request):     #s=""     #for data in request.POST:     #   s="%s,%s" % (s,data)     s=request.POST['b']     return HttpResponse("%s" % s) 

I know its not giving Json but I'm having the problem mentioned above when i make POST request in terminal

curl http://127.0.0.1:8000/add/ -d b=2 >> output.html 

I am new to django though.

like image 865
Zabi Avatar asked Mar 16 '12 14:03

Zabi


2 Answers

First, make sure that you send the request to http://127.0.0.1/add/ not http://127.0.0.1/add.

Secondly, you may also want to exempt the view from csrf processing by adding the @csrf_exempt decorator - since you aren't sending the appropriate token from cURL.

like image 56
Burhan Khalid Avatar answered Oct 05 '22 06:10

Burhan Khalid


For URL consistency, Django has a setting called APPEND_SLASH, that always appends a slash to the end of the URL if it wasn't sent that way to begin with. This ensures that /my/awesome/url/ is always served from that URL instead of both /my/awesome/url and /my/awesome/url/.

However, Django does this by automatically redirecting the version without the slash at the end to the one with the slash at the end. Redirects don't carry the state of the request with them, so when that happens your POST data is dropped.

All you need to do is ensure that when you send your POST, you send it to the version with the slash at the end.

like image 24
Chris Pratt Avatar answered Oct 05 '22 06:10

Chris Pratt