Last active
October 25, 2018 15:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for sharing. I think this is definitely brilliant. And incredibly simple.