67

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.

Cyril N.
  • 38,875
  • 36
  • 142
  • 243

8 Answers8

105

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.

starball
  • 20,030
  • 7
  • 43
  • 238
Ni Xiaoni
  • 1,639
  • 2
  • 13
  • 10
47

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.

Community
  • 1
  • 1
  • 4
    As of Django 1.4, ``request.raw_post_data`` has been renamed ``request.body``, and ``raw_post_data`` was removed in Django 1.6. – user85461 Nov 16 '14 at 22:21
  • Actually you can make Django handle PUT and DELETE requests as you like. Here you can find a [possible approach](https://baxeico.wordpress.com/2014/06/25/put-and-delete-http-requests-with-django-and-jquery/). – Augusto Destrero Feb 12 '15 at 16:00
  • This Malcom in the google thread has by far no understanding of what he is talking about, his justification is ridiculous. The fact that the Django Core team did not even dare implementing such support in 11 years is awful... – Simon Ninon Mar 28 '19 at 18:25
14

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

jameshfisher
  • 34,029
  • 31
  • 121
  • 167
Arthur Debert
  • 10,237
  • 5
  • 26
  • 21
8

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()
Eugene Kovalev
  • 3,407
  • 1
  • 15
  • 17
5

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

Tom Christie
  • 33,394
  • 7
  • 101
  • 86
1

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)

Cuyler Quint
  • 186
  • 2
  • 6
1

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}")
JP Zhang
  • 767
  • 1
  • 7
  • 27
1

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)})
Jian
  • 191
  • 1
  • 9