How to filter events by month in Django?
Problem
I have below Django views to filter events based on the month
class FilterByMonthView(ListView): model = Event template_name = 'your_template.html' context_object_name = 'filtered_data'
def get_queryset(self): month = self.kwargs.get('month') month = str(month).zfill(2)
# Construct a date range for the specified month start_date = datetime.strptime(f'2023-{month}-01 00:00:00', '%Y-%m-%d %H:%M:%S') end_date = datetime.strptime(f'2023-{month}-01 23:59:59', '%Y-%m-%d %H:%M:%S') # Assuming end of the month
# Filter the data based on the date range queryset = Event.objects.filter( event_date__range=(start_date, end_date) ) return queryset |
Below are my models.py
class Event(models.Model): emp_id = models.IntegerField(max_length=50) event_type = models.CharField(max_length=50) event_date = models.DateTimeField() email = models.EmailField()
def __str__(self): return f"{self.event_type} {self.event_date} {self.email}" |
In the Django admin page when I am creating an event, I see the below output
ID Emp id Event type Event date Email 6 67565 Birthday Nov. 15,2010,6 a.m. jhad@jhsd.com |
Below is the urls.py for the project level and app level respectively
urlpatterns = [ path('admin/', admin.site.urls), path('emp/', include('EVENTS.urls')),
]
from django.urls import path from .views import FilterByMonthView
urlpatterns = [ path('filter/<int:month>/', FilterByMonthView.as_view(), name='filter-by-month'), ] |
HTML looks as below
<!DOCTYPE html> <html> <head> <title>Filtered Events</title> </head> <body> <h1>Events for the Selected Month</h1> <ul> {% for event in filtered_data %} <li>{{ event.event_date }} - {{ event.event_name }}</li> <!-- Display other event attributes as needed --> {% empty %} <li>No events found for this month.</li> {% endfor %} </ul> </body> </html> |
I am seeing "No events found for this month." in my browser.
below is the sample URL that I am using
http://127.0.0.1:8000/emp/filter/11/
I suspect the issue seems to be with the date format. But not sure. Please suggest
Solution
The year in your table is, 2010, hence that is outside the range.
But if you only want to match the month, not the year, you are overcomplicating things a lot. You can just work with:
class FilterByMonthView(ListView): model = Event template_name = 'your_template.html' context_object_name = 'filtered_data'
def get_queryset(self): return ( super().get_queryset().filter(event_date__month=self.kwargs['month']) ) |
Answered by: >Willem Van Onsem
Credit: >StackOverflow
Blog Links:
>Sorting the restframework in Django
>Ways to access instances of models in view in order to save both forms at once in Django
>What makes index.html have such kind of name in Django?
>Fix Module Not Found during Deployment- Django
>Creating a Django with existing directories, files, etc.?
>How to Read a CSV file with PHP using cURL?