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. 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, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.