How to use the bootstrap-datepicker in Django app?

前端 未结 5 2201
北荒
北荒 2020-12-19 03:17

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:

5条回答
  •  时光说笑
    2020-12-19 03:54

    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

    class MyModel(models.Model):
        ...
        date = models.DateField()
        ...
    

    forms.py

    class MyForm(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

    {{ form.date }}

    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.
        })
    });
    

提交回复
热议问题