Login

Combined CreateView and UpdateView

Author:
dannygale
Posted:
June 19, 2015
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

By combining the CreateView and UpdateView, you can significantly reduce repetition when processing complex forms (for example, with multiple inline formsets), by only writing the get_context_data and form_valid functions once.

This class can be used just like a normal CreateView or UpdateView.

Note that if you're trying to use it as an UpdateView but it cannot find the requested object, it will behave as a CreateView, rather than showing a 404 page.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#############################################################################
#
# Create/Update view
#
#############################################################################
from django.views.generic.detail import SingleObjectTemplateResponseMixin
from django.views.generic.edit import ModelFormMixin, ProcessFormView
class CreateUpdateView(SingleObjectTemplateResponseMixin, ModelFormMixin,
        ProcessFormView):

    def get_object(self, queryset=None):
        try:
            return super(CreateUpdateView,self).get_object(queryset)
        except AttributeError:
            return None

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        return super(CreateUpdateView, self).get(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        return super(CreateUpdateView, self).post(request, *args, **kwargs)

More like this

  1. Add custom fields to the built-in Group model by jmoppel 1 month, 1 week ago
  2. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 4 months, 3 weeks ago
  3. Python Django CRUD Example Tutorial by tuts_station 5 months, 1 week ago
  4. Browser-native date input field by kytta 6 months, 3 weeks ago
  5. Generate and render HTML Table by LLyaudet 7 months ago

Comments

Please login first before commenting.