Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for Django Class based views and having multiple forms on a single page examples

I have been looking long and far for how to have 2 unique forms displayed on one page using the newer Django class based views method.

Can anybody reference anything? Or provide a basic example. Google is not being my "friend" for this.

like image 873
bmiskie Avatar asked Aug 09 '12 20:08

bmiskie


1 Answers

The key is that you don't even have to use one of the FormView subclasses to process forms. You just have to add the machinery for processing the form manually. In the case where you do use a FormView subclass, it will only process 1 and only 1 form. So if you need two forms, you just have to handle the second one manually. I'm using DetailView as a base class just to show that you don't even have to inherit from a FormView type.

class ManualFormView(DetailView):
    def get(self, request, *args, **kwargs):
        self.other_form = MyOtherForm()
        return super(ManualFormView, self).get(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        self.other_form = MyOtherForm(request.POST)
        if self.other_form.is_valid():
            self.other_form.save() # or whatever
            return HttpResponseRedirect('/some/other/view/')
        else:
            return super(ManualFormView, self).post(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(ManualFormView, self).get_context_data(**kwargs)
        context['other_form'] = self.other_form
        return context
like image 153
Chris Pratt Avatar answered Nov 04 '22 07:11

Chris Pratt