Login

CBV to mix FormView and DetailView functionalities

Author:
pakal
Posted:
June 21, 2019
Language:
Python
Version:
Not specified
Tags:
view form cbv detail
Score:
0 (after 0 ratings)

Use this to display an object on a page AND be able to process a form on this page.

This is just a copy of the Django docs advice, but put as a reusable, standalone View.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class FormAndDetailView(FormMixin, DetailView):
    """
    Class based view to make form and detail views work together properly.
    """

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["form"] = self.get_form()
        return context

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        form = self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

More like this

Comments

Please login first before commenting.