I have a filter on which I've set a date range filter.
class UtenteActivityFilter(django_filters.FilterSet):
date = django_filters.DateFromToRangeFilter(widget=RangeWidget(attrs={"class": "form-control"}))
class Meta:
model = Activity
fields = ['date']
I am using this filter to populate a table.
class UtenteDetail(LoginRequiredMixin, DetailView):
model = Utente
template_name = 'users/utente_detail.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
f = UtenteActivityFilter(self.request.GET, queryset=Activity.objects.filter(author=self.object))
context['filter'] = f
return context
Now my table is populated by all the data from the queryset when I load the page without any date set in the filter.
How do I set the initial state of the filter to a defined value (or queryset)?
I wish my table to show just activities from "today" when the page is ofirst opened, but to still be able to filter among all the models.
I already defined a qs of activities for "today":
# context['today_activities'] = Activity.objects.filter(created__gte=timezone.now().replace(hour=0,minute=0,second=0))
but setting it as a queryset restrict the filtering to that only
One way to do this, it's by redefining the qs
property.
@property
def qs(self):
parent = super().qs
if not self.is_valid():
# add default daterange for today
start_date = timezone.now().replace(hour=0, minute=0, second=0)
end_date = timezone.now().replace(hour=23, minute=59, second=59)
field_name = "date"
lookup_gte = "%s__gte" % (field_name)
lookup_lte = "%s__lte" % (field_name)
kwargs = {lookup_gte: start_date, lookup_lte: end_date}
return parent.filter(**kwargs)
else:
return parent
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.