Login

CBV to mix FormView and DetailView functionalities

Author:
pakal
Posted:
June 21, 2019
Language:
Python
Version:
Not specified
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

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.