Skip to content

Instantly share code, notes, and snippets.

@SmileyChris
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SmileyChris/7e64be546d5318208c74 to your computer and use it in GitHub Desktop.
Save SmileyChris/7e64be546d5318208c74 to your computer and use it in GitHub Desktop.
class UpdateOrCreateMixin(object):
"""
A view mixin to allow views that use SingleObjectMixin to not fail if no pk/slug is provided.
Primarily useful for making an UpdateView that can create objects too. For example::
class MyView(UpdateOrCreateMixin, UpdateView):
...
url(r'^add/$', MyView.as_view(), name='my-add-view'),
"""
def get_object(self, *args, **kwargs):
"""
Catch the failure exception of SingleObjectMixin and just return None.
"""
try:
return super(UpdateOrCreateMixin, self).get_object(*args, **kwargs)
except AttributeError:
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment