Home > front end >  How Can I Filter By Date Range Using Djangos Built in ListView?
How Can I Filter By Date Range Using Djangos Built in ListView?

Time:01-03

I'm quite new to Django and everywhere I look seems to offer a solution that works for generic function based views, or really overcomplicates what i'm trying to do with a class based view.

All I want to do is to filter out the results from a ListView to only include entries from a selected date range.

For example I have a generic Class based view:

class HomeView(ListView):
model = Post
template_name = 'home.html'

that returns all of my blog posts

and a very simple date selector on my home.html page:

From date: <input type="date" name="fromdate"/>
To Date: <input type="date" name="todate"/>
<input type="submit" value="search"/>

How can I take the input from the simple date range and alter my class based view to: IF a date range has been selected: only show posts from within that date range?

Thank you in advance. I have checked and I can not see anywhere that has answered this on here that uses ListView or that doesn't overcomplicate the problem and become close to impossible to follow for a beginner

Thank you

CodePudding user response:

One of the easy way is to over-ride the queryset.

Get the daterange from the request, and filter the queryset using it.

class HomeView(ListView):
    model = Post
    template_name = 'home.html'

    def get_queryset(self):
        from_date = self.request.GET.get('fromdate')
        to_date = self.request.GET.get('todate')
        self.queryset = Post.objects.all()
        if from_date:
            self.queryset.filter(from_date__gte=from_date)
        if to_date:
            self.queryset.filter(to_date__lte=to_date)
        return self.queryset
  • Related