Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Responding to a form POST in a subclass of DetailView

Tags:

django

I have a view that uses one of the class-based generic views (derives from django.views.generic.DetailView), with a custom form:

from django.views.generic import DetailView

class MyDetailView(DetailView):
    model=MyModel

    def get_object(self):
        object = MyModel.objects.get(uuid=self.kwargs['uuid'])

    def get_context_data(self, **kwargs):
        form = MyForm
        context = super(MyDetailView, self).get_context_data(**kwargs)
        context['form'] = form
        return context

I'd like the POST for the form submission to go to the same URL as the GET. Is it possible to modify this view code so that it can also respond to the POST? If so, how? Do I need to inherit from another mixin class? And what is the name of the method to add to process the form data?

Or is it just a bad idea to respond to the POST at the same URL for this scenario?

(Note: the form is not modifying the MyModel object being displayed. Instead, it's being used to create a model object of a different type, so UpdateView isn't reallya good fit).

like image 418
Lorin Hochstein Avatar asked Jan 11 '12 12:01

Lorin Hochstein


2 Answers

It's not quite clear what you want to do with your POST request, but it might make sense to use django.views.generic.UpdateView instead of DetailView - as it also gives you some methods to deal with form processing.

To just add handling of a POST request to the detail view a post() method should be enough!

like image 121
Bernhard Vallant Avatar answered Nov 17 '22 01:11

Bernhard Vallant


Looking at the Django code, the post() method should look like:

def post(self, request, *args, **kwargs):
    ...
like image 5
Lorin Hochstein Avatar answered Nov 16 '22 23:11

Lorin Hochstein