I\'d like to follow the RESTful pattern for my new django project, and I\'d like to know where the parameters are when a PUT/DELETE request is made.
As far as I know
Ninefiger's answer is correct. There are, however, workarounds for that.
If you're writing a REST style API for a Django project, I strongly suggest you use tastypie. You will save yourself tons of time and guarantee a more structured form to your API. You can also look at how tastypie does it (access the PUT and DELETE data).
There was a problem that I couldn't solve how to parse multipart/form-data from request
. QueryDict(request.body)
did not help me.
So, I've found a solution for me. I started using this:
from django.http.multipartparser import MultiPartParser
You can get data from request
like:
MultiPartParser(request.META, request, request.upload_handlers).parse()
I assume what you're asking is if you can have a method like this:
def restaction(request, id):
if request.method == "PUT":
someparam = request.PUT["somekey"]
The answer is no, you can't. Django doesn't construct such dictionaries for PUT, OPTIONS and DELETE requests, the reasoning being explained here.
To summarise it for you, the concept of REST is that the data you exchange can be much more complicated than a simple map of keys to values. For example, PUTting an image, or using json. A framework can't know the many ways you might want to send data, so it does the obvious thing - let's you handle that bit. See also the answer to this question where the same response is given.
Now, where do you find the data? Well, according to the docs, django 1.2 features request.raw_post_data
. As a heads up, it looks like django 1.3 will support request.read()
i.e. file-like semantics.
My approach was to override the dispatch function so I can set a variable from the body data using QueryDict()
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import QueryDict
from django.views.generic import View
class GenericView(View):
def dispatch(self, request, *args, **kwargs):
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
# if we have a request with potential body data utilize QueryDict()
if request.method.lower() in ['post', 'put', 'patch']:
self.request_body_data = {k: v[0] if len(v)==1 else v for k, v in QueryDict(request.body).lists()}
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)
class ObjectDetailView(LoginRequiredMixin, GenericView):
def put(self, request, object_id):
print("updating object", object_id)
print(self.request_body_data)
def patch(self, request, object_id):
print("updating object", object_id)
print(self.request_body_data)
I am using django v1.5. And I mainly use QueryDict to solve the problem:
from django.http import QueryDict
put = QueryDict(request.body)
description = put.get('description')
and in *.coffee
$.ajax
url: "/policy/#{policyId}/description/"
type: "PUT"
data:
description: value
success: (data) ->
alert data.body
fail: (data) ->
alert "fail"
You can go here to find more information. And I hope this can help you. Good luck:)
Django cannot access params in the body of PUT
request easily. My workaround:
def coerce_put_post(request):
"""
Django doesn't particularly understand REST.
In case we send data over PUT, Django won't
actually look at the data and load it. We need
to twist its arm here.
The try/except abominiation here is due to a bug
in mod_python. This should fix it.
"""
if request.method == "PUT":
# Bug fix: if _load_post_and_files has already been called, for
# example by middleware accessing request.POST, the below code to
# pretend the request is a POST instead of a PUT will be too late
# to make a difference. Also calling _load_post_and_files will result
# in the following exception:
# AttributeError: You cannot set the upload handlers after the upload has been processed.
# The fix is to check for the presence of the _post field which is set
# the first time _load_post_and_files is called (both by wsgi.py and
# modpython.py). If it's set, the request has to be 'reset' to redo
# the query value parsing in POST mode.
if hasattr(request, '_post'):
del request._post
del request._files
try:
request.method = "POST"
request._load_post_and_files()
#body = request.body
request.method = "PUT"
except AttributeError:
request.META['REQUEST_METHOD'] = 'POST'
request._load_post_and_files()
request.META['REQUEST_METHOD'] = 'PUT'
request.PUT = request.POST
@api_view(["PUT", "POST"])
def submit(request):
coerce_put_post(request)
description=request.PUT.get('k', 0)
return HttpResponse(f"Received {description}")