I am trying to filter by DateField using django_filters lib. Following the doc I encounter an issue with the "gte" and "lte" lookup_expressions (I tried both). The problem is that it only return results if the date I input in my datepicker is the exact date, which I would suspect would be the expected "iexact" or "exact" lookup_expression results. This is my simplified code, note that I have tried using only one date (removing end_date in both model and filter.py) and the result was the same so I don't believe this is a range issue
Model
class Replacement(models.Model):
start_date = models.DateField(
null=True, blank=True)
end_date = models.DateField(
null=True, blank=True)
filter.py
#not sure if this DateInput is related to the issue, just a way to attach "date" type so as to get a datepicker on template
class DateInput(forms.DateInput):
input_type = 'date'
class ReplacementFilter(django_filters.FilterSet):
start_date = DateFilter(field_name="start_date", lookup_expr='gte')
end_date = DateFilter(field_name="end_date", lookup_expr='gte')
class Meta:
model = Replacement
fields = ['start_date', 'end_date']
start_date = django_filters.DateFilter(
widget=DateInput(attrs={'type': 'date'}))
end_date = django_filters.DateFilter(
widget=DateInput(attrs={'type': 'date'}))
Views
def replacement_list_page(request):
replacements = Replacement.objects.all()
replacement_filter = ReplacementFilter(request.GET, queryset=replacements)
print(replacement_filter)
return render(request, "replacements/replacementlist.html", {"replacement": replacements,
'filter': replacement_filter})
Thanks
You defined start_date
and end_date
twice, once with the lookup_expr
and once with the widget
, as a result, the last defined DateFilter
s will be used, and thus ommitting the earlier defined start_date
and end_date
.
You thus should define the FilterSet
with:
class ReplacementFilter(django_filters.FilterSet):
start_date = DateFilter(
field_name='start_date',
lookup_expr='gte',
widget=DateInput(attrs={'type': 'date'}) # 🖘 specify widget
)
end_date = DateFilter(
field_name='end_date',
lookup_expr='gte',
widget=DateInput(attrs={'type': 'date'}) # 🖘 specify widget
)
class Meta:
model = Replacement
fields = ['start_date', 'end_date']
# no new definitions of start_date and end_date