How can I use Date Picker with django-filter?
It is not very clear what kind of datepicker you think of, but I assume you'd like to have something like this:
jQuery UI Datepicker
I hope you know how to use a third party JavaScript library. That should be out of the scope of this question.
Once you have set up your project to use jQuery UI you can change your filters.py
:
class AvailFilter(django_filters.FilterSet):
row_date = django_filters.DateFilter(
widget=DateInput(
attrs={
'class': 'datepicker'
}
)
)
class Meta:
# keep everything but the line widgets
Any widget you use accepts a keyword argument attrs
which takes a dictionary, where you can specify all attributes of an HTML tag.
Now when you render row_date
it should output something like this:
<input type="date" class="datepicker" ... />
type="date" can help you without any widget (depends of browser):
class AvailFilter(django_filters.FilterSet):
row_date = django_filters.DateFilter(widget=DateInput(attrs={'type': 'date'}))
also if you need date range filter, you can use DateFromToRangeFilter instead of DateFilter
To provide another answer similar to cezar's answer, I did it this way below with my filter and template codes.
filter.py
import django_filters
from .models import Product
from django import forms
class ProductFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains')
price = django_filters.NumberFilter()
# using jquery
djfdate_time = django_filters.DateFilter(
lookup_expr='icontains',
widget=forms.DateInput(
attrs={
'id': 'datepicker',
'type': 'text'
}
)
)
class Meta:
model = Product
fields = ['name', 'djfdate_time','price']
base.html
{% load static %}
<html>
<head>
<link rel="stylesheet" type="text/css" href="{% static 'css/search.css' %}">
<title></title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div id="header">
<h1 ><a class="searchtitle" href="/">Django Filter Example</a></h1>
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
<script>
$( function() {
$( "#datepicker" ).datepicker();
} );
</script>
</body>
</html>
base_extension.html
{% extends "base.html" %}
{% load my_templatetags %}
{% block content %}
<form action="" method="get">
<div>Name{{ filter.form.name }}</div>
<div>Price{{ filter.form.price }}</div>
<div>Date_Time{{ filter.form.djfdate_time }}</div>
<input type="submit" />
</form>
{% for obj in dataqs.object_list %}
{{ obj.name }}
<div>
<li>${{ obj.price }}</li>
<li> {{ obj.djfdate_time|date:'m-d H:i:s.u' }}</li>
</div>
{% endfor %}
{% endblock %}