Django - Where are the params stored on a PUT/DELETE request?

DjangoRestParameters

Django Problem Overview


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, I only see GET & POST QueryDict in the request, no others. Is Django adding a new PUT or DELETE QueryDict regarding to the request, or does it add the parameters to GET or POST QueryDict ?

Thanks for your help.

Django Solutions


Solution 1 - Django

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:)

Solution 2 - Django

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.

Solution 3 - Django

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).

Solution 4 - Django

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()

Solution 5 - Django

You can see an example of getting a QueryDict for a PUT method in django-piston's code (See the coerce_put_post method)

Solution 6 - Django

As long as the parameters are in the URL, you can still use self.request.GET to get parameters for PUT and DELETE methods.

For example

DELETE /api/comment/?comment_id=40 HTTP/1.1

In the APIView you can do this:

class CommentAPIView(APIView):

    # ... ...

    def delete(self, request):
        user = request.user.id
        comment_id = self.request.GET['comment_id']
        try:
            cmt = get_object_or_404(Comment, id=comment_id, user=user)
            cmt.delete()
            return Response(status=204)
        except Exception, e:
            return Response({'error': str(e)})

Solution 7 - Django

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)

Solution 8 - Django

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}")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCyril N.View Question on Stackoverflow
Solution 1 - DjangoNi XiaoniView Answer on Stackoverflow
Solution 2 - Djangouser257111View Answer on Stackoverflow
Solution 3 - DjangoArthur DebertView Answer on Stackoverflow
Solution 4 - DjangoEugene KovalevView Answer on Stackoverflow
Solution 5 - DjangoTom ChristieView Answer on Stackoverflow
Solution 6 - DjangoJianView Answer on Stackoverflow
Solution 7 - DjangoCuyler QuintView Answer on Stackoverflow
Solution 8 - DjangoJP ZhangView Answer on Stackoverflow