2020-02-24 22:28:52 +00:00
|
|
|
from django.shortcuts import get_object_or_404
|
2016-12-25 14:52:55 +00:00
|
|
|
|
2021-07-19 13:06:10 +00:00
|
|
|
from camps.models import Camp
|
|
|
|
|
2016-12-25 14:52:55 +00:00
|
|
|
|
2020-02-22 13:50:09 +00:00
|
|
|
class CampViewMixin:
|
2017-05-24 05:49:32 +00:00
|
|
|
"""
|
|
|
|
This mixin makes sure self.camp is available (taken from url kwarg camp_slug)
|
2019-03-28 06:04:53 +00:00
|
|
|
It also filters out objects that belong to other camps when the queryset has a camp_filter
|
2017-05-24 05:49:32 +00:00
|
|
|
"""
|
2018-06-20 20:03:29 +00:00
|
|
|
|
2020-02-22 13:50:09 +00:00
|
|
|
def setup(self, *args, **kwargs):
|
|
|
|
super().setup(*args, **kwargs)
|
2018-06-20 20:03:29 +00:00
|
|
|
self.camp = get_object_or_404(Camp, slug=self.kwargs["camp_slug"])
|
2016-12-25 14:52:55 +00:00
|
|
|
|
|
|
|
def get_queryset(self):
|
2018-07-17 20:43:16 +00:00
|
|
|
queryset = super().get_queryset()
|
2018-07-17 22:46:38 +00:00
|
|
|
|
|
|
|
# if this queryset is empty return it right away, because nothing for us to do
|
|
|
|
if not queryset:
|
|
|
|
return queryset
|
|
|
|
|
2019-03-28 06:04:53 +00:00
|
|
|
# do we have a camp_filter on this model
|
2019-06-16 12:32:24 +00:00
|
|
|
if not hasattr(self.model, "camp_filter"):
|
2019-03-28 06:04:53 +00:00
|
|
|
return queryset
|
|
|
|
|
2018-07-17 22:46:38 +00:00
|
|
|
# get the camp_filter from the model
|
|
|
|
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:
|
|
|
|
# add camp to the filter_dict
|
|
|
|
filter_dict = {_filter: self.camp}
|
|
|
|
|
|
|
|
# get pk from kwargs if we have it
|
2019-06-16 12:32:24 +00:00
|
|
|
if hasattr(self, "pk_url_kwarg"):
|
2018-07-17 22:46:38 +00:00
|
|
|
pk = self.kwargs.get(self.pk_url_kwarg)
|
|
|
|
if pk is not None:
|
|
|
|
# We should also filter for the pk of the object
|
2019-06-16 12:32:24 +00:00
|
|
|
filter_dict["pk"] = pk
|
2018-07-17 22:46:38 +00:00
|
|
|
|
|
|
|
# get slug from kwargs if we have it
|
2019-06-16 12:32:24 +00:00
|
|
|
if hasattr(self, "slug_url_kwarg"):
|
2018-07-17 22:46:38 +00:00
|
|
|
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
|
|
|
|
|
|
|
|
# do the filtering and return the result
|
|
|
|
result = queryset.filter(**filter_dict)
|
|
|
|
if result.exists():
|
|
|
|
# we got some results with this camp_filter, return now
|
|
|
|
return result
|
|
|
|
|
|
|
|
# no camp_filter returned any results, return an empty queryset
|
|
|
|
return result
|