How to add bootstrap 4 datepicker in django

Viewed 2686

I have been trying to add bootstrap 4 datepicker from this tutorial. It works great when I add a new record but problem is when editing the record, the value has not appeared in the field. What I have done is:

widgets.py

from django.forms import DateTimeInput, DateInput

class BootstrapDateTimePickerInput(DateTimeInput):
    template_name = 'widgets/bootstrap_datetimepicker.html'

    def get_context(self, name, value, attrs):
        datetimepicker_id = 'datetimepicker_{name}'.format(name=name)
        if attrs is None:
            attrs = dict()
        attrs['data-target'] = '#{id}'.format(id=datetimepicker_id)
        attrs['class'] = 'form-control datetimepicker-input'
        context = super().get_context(name, value, attrs)
        context['widget']['datetimepicker_id'] = datetimepicker_id
        return context

forms.py

class ClaimForm(forms.ModelForm):

    purchase_date = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M'], widget=BootstrapDateTimePickerInput())

    class Meta(forms.ModelForm):
        model = Claim
        fields = ['store', 'expense', 'rewards', 'money_receipt', 'purchase_date']

I want to add the date value into the input field when I edit the form. enter image description here

1 Answers

We have built a Django Python package for Bootstrap 4 date and time picker widgets on top of the Tempus Dominus JS library. Details are here:

https://pypi.org/project/django-tempus-dominus/

For your case, something like this would work:

from tempus_dominus.widgets import DateTimePicker

purchase_date = forms.DateTimeField(
    widget=DateTimePicker(),
    initial='1980-01-01 12:00:00',
)

Good luck!

Related