Search code examples
djangodatepickerdjango-filter

How can I use Date Picker with django-filter?


I am trying to figure out how can I use datepicker with django-filter. I have tried a bunch of widgets but it's not working. Any suggestions will be appreciated!

I want to use datepicker for the row_date search filter.

filters.py

from home2.models import AvailstaticCopy
from django import forms

import django_filters

class DateInput(forms.DateInput):
    input_type = 'date'

class AvailFilter(django_filters.FilterSet):

    class Meta:
        model   = AvailstaticCopy
        widgets = {'row_date': DateInput(),}
        fields  = ['row_date', 'director','manager','analyst',]

This is my template

{% load widget_tweaks %}
<form method="get">
  <div class="well">
    <h4 style="margin-top: 0">Filter</h4>
    <div class="row">
      <div class="form-group col-sm-4 col-md-3">
        {{ filter.form.row_date.label_tag }}
        {% render_field filter.form.row_date class="form-control" %}
      </div>
      <div class="form-group col-sm-4 col-md-3">
        {{ filter.form.director.label_tag }}
        {% render_field filter.form.director class="form-control" %}
      </div>
      <div class="form-group col-sm-8 col-md-6">
        {{ filter.form.manager.label_tag }}
        {% render_field filter.form.manager class="form-control" %}
      </div> 
      <div class="form-group col-sm-8 col-md-6">
        {{ filter.form.analyst.label_tag }}
        {% render_field filter.form.analyst class="form-control" %}
      </div> 
      <div class="form-group col-sm-8 col-md-6">
        <button type="submit" class="btn btn-primary">
          <span class="glyphicon glyphicon-search"></span> Search
        </button>
      </div>
    </div>
  </div>
</form>

Solution

  • 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" ... />