Sorry if this is a trivial question but I've been searching around for quite sometime and have been unable to find a good implementation.
Can someone provide an example of how to implement a post-only view (that can handle file uploads) in Django by subclassing any of the generic views?
I want to create an endpoint which handles all blog post comment creation logic. The comment form is embedded on my blog page and thus, this data will be sent to the url as POST
.
For Django class-based views we access an appropriate view function by calling the class method as_view() . This does all the work of creating an instance of the class, and making sure that the right handler methods are called for incoming HTTP requests.
Django Redirects: A Super Simple Example Just call redirect() with a URL in your view. It will return a HttpResponseRedirect class, which you then return from your view. Assuming this is the main urls.py of your Django project, the URL /redirect/ now redirects to /redirect-success/ .
How to Pass Additional Context into a Class Based View (Django)? Passing context into your templates from class-based views is easy once you know what to look out for. There are two ways to do it – one involves get_context_data, the other is by modifying the extra_context variable.
To decorate every instance of a class-based view, you need to decorate the class definition itself. To do this you apply the decorator to the dispatch() method of the class. The decorators will process a request in the order they are passed to the decorator.
The View
class has an http_method_names
attribute that lists the HTTP methods that the view will accept.
Therefore, you could subclass any generic view you like (for example, CreateView
), and set http_method_names
so that only POST requests are allowed.
from django.views.generic.edit import CreateView
class CommentCreateView(CreateView):
http_method_names = ['post']
model = Comment
...
Alternatively, you could subclass View
, and write your own post method.
class CommentView(View):
def post(self, request):
...
In this case, GET requests will return a HttpResponseNotAllowed
response, because you have not defined a get
method to handle GET requests.
You could try something like:
class MyView(TemplateView):
template_name = 'my_template.html'
def post(self, request, **kwargs):
my_data = request.POST
# do something with your data
context = {} # set your context
return super(TemplateView, self).render_to_response(context)
From the docs:
dispatch looks at the request to determine whether it is a GET, POST, etc, and relays the request to a matching method if one is defined, or raises HttpResponseNotAllowed
So essentially, any class based view you create where you only define a POST
method, will only allow a POST request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With