Django Class Based View Returns Empty String When Post
Solution 1:
You need to implement its post
method. See Class based views.
from django.http import HttpResponse
from django.views.generic import View
classTestView(View):
@method_decorator(csrf_exempt)defdispatch(self, *args, **kwargs):
# do somethingreturnsuper(TestView, self).dispatch(*args, **kwargs)
defpost(self, request, *args, **kwargs):
# do somthingdefget(self, request, *args, **kwargs):
return HttpResponse('Hello, World!')
See more for dispatch
docs.
The default implementation will inspect the HTTP method and attempt to delegate to a method that matches the HTTP method; a GET will be delegated to get(), a POST to post(), and so on.
So previously you was disturbing the above logic, calling super
will allow dispatch
to delegate to post method.
Solution 2:
I know this doesn't really answer your question, but it may offer a workaround. What I have used in JSON applications is to send a post to the get method when I want the same results for both. Something like:
defget(self, request, *args, **kwargs):
return HttpResponse('Ha!')
defpost(self. request, *args, **kwargs):
returnself.get(request, *args, **kwargs)
with dispatch left alone.
Solution 3:
The best approach when using class-based views is not to write your own method handlers from scratch; instead, use one of the generic classes as the base and then modify just the methods which handle what you need. For example, if you have a form which needs to be submitted via POST, you should use the FormView as a base, which handles responses both GET and POST requests.
You don't need to override post()
and/or get()
methods themselves; instead use form_valid()
to define what happens when the form is submitted:
classTestView(FormView):
form_class = MyForm
success_url = "/your/return/url/"defform_valid(self, form):
# do somethingreturn redirect(self.get_success_url())
Solution 4:
Sorry guys, this is a bug in uWSGI and nginx ...
https://stackoverflow.com/a/11115108/41948
I am really sorry for wasting your time by misleading you. And still it took me a while to figure which part of my stack went wrong.
Post a Comment for "Django Class Based View Returns Empty String When Post"