1👍
✅
Blindly coding it, do something like this in your forms.py
:
from django import Forms
from .models import Project
class ProjectFilterForm(forms.Form):
range = forms.ChoiceField(choices=[], required=False)
def __init__(self, *args, **kwargs):
super(ProjectFilterForm, self).__init__(*args, **kwargs)
oldest = Project.objects.first()
newest = Project.objects.last()
if oldest and newest:
range_choices = []
for year in range(oldest.date.year, newest.date.year+1):
range_choices.append('Spring {}'.format(year))
range_choices.append('Fall {}'.format(year))
self.fields['range'].choices = range_choices
def get_filtered_projects(self):
if not self.is_valid():
return []
choice = self.cleaned_data['range']
parts = choice.split(' ')
month_range = [4,5,6,7,8,9] if parts[0] == 'Spring' else [10,11,12,1,2,3]
year = int(parts[1])
return Project.objects.filter(date__year=year, date__month__in=month_range)
Include the form as part of the template, and in the view use the get_filtered_projects
to generate the list of projects to show in the rendered page.
Source:stackexchange.com