106👍
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.
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.
- [Django]-Extend base.html problem
- [Django]-Django – Website Home Page
- [Django]-Python 3 list(dictionary.keys()) raises error. What am I doing wrong?
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).
- [Django]-How to run a celery worker with Django app scalable by AWS Elastic Beanstalk?
- [Django]-Users in initial data fixture
- [Django]-Unable to find a locale path to store translations for file __init__.py
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()
- [Django]-AccessDenied when calling the CreateMultipartUpload operation in Django using django-storages and boto3
- [Django]-Giving email account a name when sending emails with Django through Google Apps
- [Django]-Django – Render the <label> of a single form field
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)
- [Django]-How to disable Django's CSRF validation?
- [Django]-In Django, how does one filter a QuerySet with dynamic field lookups?
- [Django]-Manager isn't accessible via model instances
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)
- [Django]-"Post Image data using POSTMAN"
- [Django]-Django, creating a custom 500/404 error page
- [Django]-Authorization Credentials Stripped — django, elastic beanstalk, oauth
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}")
- [Django]-Django FileField upload is not working for me
- [Django]-How to query as GROUP BY in Django?
- [Django]-Why does django run everything twice?
0👍
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)})
- [Django]-Django models: mutual references between two classes and impossibility to use forward declaration in python
- [Django]-Manager isn't available; User has been swapped for 'pet.Person'
- [Django]-Django – Reverse for '' not found. '' is not a valid view function or pattern name