Last active
August 17, 2016 16:37
-
-
Save mkoistinen/45ae8ebe41706a156496dec14d5805b9 to your computer and use it in GitHub Desktop.
CustomPKMixin
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
class CustomPKMixin(object): | |
""" | |
Allows a normal SingleObjectMixin view. | |
""" | |
pk_field = None | |
def get_object(self, queryset=None): | |
""" | |
Returns the object the view is displaying. | |
By default this requires `self.queryset` and a `pk` or `slug` argument | |
in the URLconf, but subclasses can override this to return any object. | |
""" | |
# Use a custom queryset if provided; this is required for subclasses | |
# like DateDetailView | |
if queryset is None: | |
queryset = self.get_queryset() | |
# Next, try looking up by primary key. | |
pk = self.kwargs.get(self.pk_url_kwarg, None) | |
slug = self.kwargs.get(self.slug_url_kwarg, None) | |
if pk is not None: | |
# ONLY LINES THAT CHANGE ARE HERE vvvv | |
if self.pk_field is None: | |
self.pk_field = 'pk' | |
queryset = queryset.filter(**{self.pk_field: pk}) | |
# ONLY LINES THAT CHANGE ARE HERE ^^^^ | |
# Next, try looking up by slug. | |
elif slug is not None: | |
slug_field = self.get_slug_field() | |
queryset = queryset.filter(**{slug_field: slug}) | |
# If none of those are defined, it's an error. | |
else: | |
raise AttributeError("Generic detail view %s must be called with " | |
"either an object pk or a slug." | |
% self.__class__.__name__) | |
try: | |
# Get the single item from the filtered queryset | |
obj = queryset.get() | |
except ObjectDoesNotExist: | |
raise Http404(_("No %(verbose_name)s found matching the query") % | |
{'verbose_name': queryset.model._meta.verbose_name}) | |
return obj |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment