Skip to content Skip to sidebar Skip to footer

How To Use The Bootstrap-datepicker In Django App?

I want to use the bootstrap-datepicker (https://bootstrap-datepicker.readthedocs.org) in my django application. I use Django 1.7. In index.html file I have: ><linkrel="stylesheet"href="{% static 'my_app/css/bootstrap.min.css' %}"><linkrel="stylesheet"href="{% static 'my_app/css/datepicker.css' %}"><scriptsrc="//code.jquery.com/jquery-1.11.2.min.js"></script><linkrel="stylesheet"href="{% static 'my_app/js/bootstrap-datepicker.js' %}"><script> $(document).ready(function(){ $('.datepicker').datepicker(); }); </script>

I know this hasn't been answered in a few months but wanted to post this just to make sure this might help any one else.

Solution 2:

For DJango version 2.1, 2.0, 1.11, 1.10 and 1.8

To use Bootstrap date-picker in your Django app install django-bootstrap-datepicker-plus, follow the installation instructions on the GitHub page to configure it, then you can use it in Custom Forms and Model Forms as below.

Usage in Custom Forms:

from bootstrap_datepicker_plus import DatePickerInput

classToDoForm(forms.Form):
    user = forms.CharField()
    date_from = forms.DateField(widget = DatePickerInput())

Usage in Model Forms:

from bootstrap_datepicker_plus import DatePickerInput

classMyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ['user', 'date_from', 'date_to']
        widgets = {
            'date_form': DatePickerInput(),
            'date_to': DatePickerInput()
        }

Usage with django-filters:

from bootstrap_datepicker_plus import DatePickerInput

classFilter(django_filters.FilterSet):
   class Meta:
        model = MyModel
        fields = ['user', 'date_from', 'date_to']
        widgets = {'date': DatePickerInput()}

Disclaimer:This django package is maintained by me. For any issues with it please open issues on the Github Page instead of putting comments here.

Solution 3:

(Django 2.1, 1.11 and python >2.7 and > 3.4 compatible) Working and reusable solution, custom from bootstrap-datepicker:

import re
from django.conf import settings
from django.utils.translation import get_language
from django import forms
from django.utils import formats, timezone

classBootstrapDatePicker(forms.DateInput):
    format_re = re.compile(r'(?P<part>%[bBdDjmMnyY])')

    def__init__(self, attrs=None, format=None):
        '''
        for a list of useful attributes see:
        http://bootstrap-datepicker.readthedocs.io/en/latest/options.html

        Most options can be provided via data-attributes. An option can be
        converted to a data-attribute by taking its name, replacing each
        uppercase letter with its lowercase equivalent preceded by a dash, and
        prepending "data-date-" to the result. For example, startDate would be
        data-date-start-date, format would be data-date-format, and
        daysOfWeekDisabled would be data-date-days-of-week-disabled.
        '''# final_attrs provides:# - data-provide: apply datepicker to inline created inputs# - data-date-language: apply the current language# - data-date-format: apply the current format for dates
        final_attrs = {
            'data-provide': 'datepicker',
            'data-date-language': get_language(),
            'data-date-format': self.get_date_format(format=format),
            'data-date-autoclose': 'true',
            'data-date-clear-btn': 'true',
            'data-date-today-btn': 'linked',
            'data-date-today-highlight': 'true',
        }
        if attrs isnotNone:
            classes = attrs.get('class', '').split(' ')
            classes.append('datepicker')
            attrs['class'] = ' '.join(classes)
            final_attrs.update(attrs)
        super(BootstrapDatePicker, self).__init__(attrs=final_attrs, format=format)

    defget_date_format(self, format=None):
        format_map = {
            '%d': 'dd',
            '%j': 'd',
            '%m': 'mm',
            '%n': 'm',
            '%y': 'yy',
            '%Y': 'yyyy',
            '%b': 'M',
            '%B': 'MM',
        }
        ifformatisNone:
            format = formats.get_format(self.format_key)[0]
        return re.sub(self.format_re, lambda x: format_map[x.group()], format)

    @propertydefmedia(self):
        root = 'vendor/bootstrap-datepicker'
        css = {'screen': ('vendor/bootstrap-datepicker/css/bootstrap-datepicker3.min.css',)}
        js = ['%s/js/bootstrap-datepicker.min.js' % root]
        js += ['%s/locales/bootstrap-datepicker.%s.min.js' % (root, lang) for lang, _ in settings.LANGUAGES]
        return forms.Media(js=js, css=css)

Then I implemented my form using BootstrapDatePicker custom class:

classMyModelForm(BootstrapForm, forms.ModelForm):

    classMeta:
        model = myModelfields= ('field1', 'field2', 'date')
        widgets = {
            'data': BootstrapDateTimePicker(attrs={'class': 'form-control'}),
        }

Finally I included js/css in the template.

Solution 4:

While there is a python package that seems to solve this quite well I chose to see if I could make the datepicker work using Django's widget class to render datepicker attributes, mentioned in the docs.

Note, I am only using a date field and not a date time field because I do not need my app to support times in this instance.

models.py

classMyModel(models.Model):
    ...
    date = models.DateField()
    ...

forms.py

classMyForm(forms.Form):
    ...

    '''
    Here I create a dict of the HTML attributes
    I want to pass to the template.
    '''
    DATEPICKER = {
        'type': 'text',
        'class': 'form-control',
        'id': 'datetimepicker4'
    }
    # Call attrs with form widget
    date = forms.DateField(widget=forms.DateInput(attrs=DATEPICKER))
    ...

template.html

<divclass="form-group"><divclass='input-group date'id='datetimepicker1'>
    {{ form.date }}
    <spanclass="input-group-addon"><spanclass="glyphicon glyphicon-calendar"></span></span></div></div>

JS

$(function () {
    $('#datetimepicker1').datetimepicker({
        format: 'YYYY-MM-DD'//This is the default date format Django will accept, it also disables the time in the datepicker.
    })
});

Post a Comment for "How To Use The Bootstrap-datepicker In Django App?"