Skip to content

Instantly share code, notes, and snippets.

@vdboor
Last active October 25, 2018 15:12
Show Gist options
  • Save vdboor/dbc53b05a7a9424c2cfb to your computer and use it in GitHub Desktop.
Save vdboor/dbc53b05a7a9424c2cfb to your computer and use it in GitHub Desktop.
A CreateOrUpdateView for Django, to support both creating and updating an object in a single view
"""
An create+update view in a single class.
"""
from django.views.generic.detail import SingleObjectTemplateResponseMixin
from django.views.generic.edit import ModelFormMixin, ProcessFormView
class BaseCreateOrUpdateView(ModelFormMixin, ProcessFormView):
"""
Merging the logic of Django's
:class:`~django.views.generic.edit.BaseCreateView` and
:class:`~django.views.generic.edit.BaseUpdateView`
Just like the the base views in Django, this class level
don't have a ``render_to_response`` and only provide the workflow logic.
"""
def _setup(self):
if self.pk_url_kwarg in self.kwargs or self.slug_url_kwarg in self.kwargs:
# Edit view
self.object = self.get_object()
self.is_add = False
else:
# Add view
self.object = None
self.is_add = True
def get(self, request, *args, **kwargs):
self._setup()
return super(BaseCreateOrUpdateView, self).get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
self._setup()
return super(BaseCreateOrUpdateView, self).post(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super(BaseCreateOrUpdateView, self).get_context_data(**kwargs)
context['is_add'] = self.is_add
return context
class CreateOrUpdateView(SingleObjectTemplateResponseMixin, BaseCreateOrUpdateView):
"""
Merging the logic of Django's
:class:`~django.views.generic.edit.CreateView` and
:class:`~django.views.generic.edit.UpdateView`
This provides the class to inherit from for standard views.
"""
template_name_suffix = '_form'
@CostantinoGrana
Copy link

Thank you for sharing. I think this is definitely brilliant. And incredibly simple.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment