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:
(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
class BootstrapDatePicker(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 is not None:
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)
def get_date_format(self, format=None):
format_map = {
'%d': 'dd',
'%j': 'd',
'%m': 'mm',
'%n': 'm',
'%y': 'yy',
'%Y': 'yyyy',
'%b': 'M',
'%B': 'MM',
}
if format is None:
format = formats.get_format(self.format_key)[0]
return re.sub(self.format_re, lambda x: format_map[x.group()], format)
@property
def media(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:
class MyModelForm(BootstrapForm, forms.ModelForm):
class Meta:
model = myModel
fields = ('field1', 'field2', 'date')
widgets = {
'data': BootstrapDateTimePicker(attrs={'class': 'form-control'}),
}
Finally I included js/css in the template.
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
class ToDoForm(forms.Form):
user = forms.CharField()
date_from = forms.DateField(widget = DatePickerInput())
Usage in Model Forms:
from bootstrap_datepicker_plus import DatePickerInput
class MyForm(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
class Filter(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.
Update: Warning, this suggestion uses the dateTIMEpicker instead of datepicker. I suggested this because you don't have to use the time functionality of the datetimepicker, so it was quite handy in my case.
Since I have been trying to get datetimepicker to work (in combination with a model form) for quite some time, I thought I would post the solution, that feels like an accumulation of all stackoverflow posts on this topic ;)
So, first of all, make sure to also include moment.js, as it is required by bootstrap-datetimepicker (see this stackoverflow post). The order is important, see the mentioned post.
Then use this site to get the type of datetimepicker you need. If you have no model form in which you want to embed the datetimepicker, you should be fine with just copying that into your html code.
If you want to make one of your model forms field a fancy datepicker (without time) field like I did, then do the following:
base.html
<script type="text/javascript" src="scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="scripts/moment-2.4.0.js"></script>
<script type="text/javascript" src="scripts/bootstrap-datetimepicker.js"></script>
forms.py
class MyForm(forms.ModelForm):
class Meta:
...
widgets = {'myDateField': forms.DateInput(attrs={'id': 'datetimepicker12'})}
...
myForm.html:
<div class="row">
...
{% bootstrap_form form %}
...
</div>
<script type="text/javascript">
$(function () {
$('#datetimepicker12').datetimepicker({
inline: true,
sideBySide: true,
format: 'DD.MM.YYYY' /*remove this line if you want to use time as well */
});
});
</script>
I hope I was able to save you some time :)
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
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
{{ form.date }}
<span class="input-group-addon">
<span class="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.
})
});
I went through similar issue. You need to call the jquery min file before any custom jquery files. so your code would look like this.
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap-theme.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/css/datepicker.css' %}">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<link rel="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.