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. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 3 months ago
  2. Python Django CRUD Example Tutorial by tuts_station 3 months, 2 weeks ago
  3. Browser-native date input field by kytta 5 months ago
  4. Generate and render HTML Table by LLyaudet 5 months, 1 week ago
  5. My firs Snippets by GutemaG 5 months, 2 weeks ago

Comments

Please login first before commenting.