2016-12-25 14:52:55 +00:00
|
|
|
from camps.models import Camp
|
|
|
|
from django.shortcuts import get_object_or_404
|
2018-06-03 15:16:00 +00:00
|
|
|
from django.utils.functional import cached_property
|
2016-12-25 14:52:55 +00:00
|
|
|
|
|
|
|
|
2016-12-28 23:15:13 +00:00
|
|
|
class CampViewMixin(object):
|
2017-05-24 05:49:32 +00:00
|
|
|
"""
|
|
|
|
This mixin makes sure self.camp is available (taken from url kwarg camp_slug)
|
|
|
|
It also filters out objects that belong to other camps when the queryset has
|
|
|
|
a direct relation to the Camp model.
|
|
|
|
"""
|
2018-06-20 20:03:29 +00:00
|
|
|
|
2016-12-25 14:52:55 +00:00
|
|
|
def dispatch(self, request, *args, **kwargs):
|
2018-06-20 20:03:29 +00:00
|
|
|
self.camp = get_object_or_404(Camp, slug=self.kwargs["camp_slug"])
|
2017-03-12 14:43:41 +00:00
|
|
|
return super().dispatch(request, *args, **kwargs)
|
2016-12-25 14:52:55 +00:00
|
|
|
|
|
|
|
def get_queryset(self):
|
2018-07-17 20:43:16 +00:00
|
|
|
queryset = super().get_queryset()
|
2017-05-24 05:49:32 +00:00
|
|
|
if queryset:
|
2018-07-16 14:07:38 +00:00
|
|
|
camp_filter = self.model.get_camp_filter()
|
|
|
|
|
|
|
|
# Let us deal with eveything as a list
|
|
|
|
if isinstance(camp_filter, str):
|
|
|
|
camp_filter = [camp_filter]
|
|
|
|
|
|
|
|
for _filter in camp_filter:
|
2018-07-17 20:43:16 +00:00
|
|
|
# add camp to the filter_dict
|
2018-07-17 18:46:30 +00:00
|
|
|
filter_dict = {_filter: self.camp}
|
2018-07-17 20:43:16 +00:00
|
|
|
|
|
|
|
# get pk from kwargs if we have it
|
2018-07-17 20:47:14 +00:00
|
|
|
if hasattr(self, 'pk_url_kwarg'):
|
|
|
|
pk = self.kwargs.get(self.pk_url_kwarg)
|
|
|
|
if pk is not None:
|
|
|
|
# We should also filter for the pk of the object
|
|
|
|
filter_dict['pk'] = pk
|
2018-07-17 20:43:16 +00:00
|
|
|
|
|
|
|
# get slug from kwargs if we have it
|
2018-07-17 20:47:14 +00:00
|
|
|
if hasattr(self, 'slug_url_kwarg'):
|
|
|
|
slug = self.kwargs.get(self.slug_url_kwarg)
|
|
|
|
if slug is not None and (pk is None or self.query_pk_and_slug):
|
|
|
|
# we should also filter for the slug of the object
|
|
|
|
filter_dict[self.get_slug_field()] = slug
|
2018-07-17 20:43:16 +00:00
|
|
|
|
|
|
|
# do the filtering and return the result
|
2018-07-17 18:46:30 +00:00
|
|
|
result = queryset.filter(**filter_dict)
|
2018-07-16 14:07:38 +00:00
|
|
|
if result.exists():
|
|
|
|
return result
|
2018-03-04 16:17:57 +00:00
|
|
|
|
2017-05-24 05:49:32 +00:00
|
|
|
# Camp relation not found, or queryset is empty, return it unaltered
|
|
|
|
return queryset
|
2018-07-17 20:43:16 +00:00
|
|
|
|