How do I use datepicker


(cix) #1

Thank you for your help so far everyone. I have come to realize that life is easy with Django crispy form been able to use but I have an issue, which is using datepicker. Tutorials I have seen make use of modelForm and I am using my bootstrap template to output the html layout.
Please how do I go about the datepicker in my template


(Vitor Freitas) #2

I like to use jQuery lib bootstrap-datetimepicker

You could render the field manually like this:

<div class="input-group datetime" id="{{ form.date.id_for_label }}_datetime">
  {{ form.date }}
  <span class="input-group-addon"><span class="fa fa-calendar"></span></span>
</div>

Then you could have this script at the bottom of your base.html template:

$(".datetime").datetimepicker({
  format: 'DD/MM/YYYY HH:mm'
});

The downside is that you would no longer be able to render the form in one shot like {{ form|crispy }}

You would need to do something like:

<div class="form-group">
    {{ form.name|as_crispy_field }}
</div>
<div class="form-group">
    <div class="input-group datetime" id="{{ form.date.id_for_label }}_datetime">
      {{ form.date }}
      <span class="input-group-addon"><span class="fa fa-calendar"></span></span>
    </div>
</div>

But I’m pretty sure there is a better way to do that, creating a custom widget for date fields. I need to research more. Maybe others can share their experience with that :smiley:


(cix) #3

Hi Vitor,
Still have issues with the datetimepicker, please could you look into the image sent to help where I might have mis-steped


(Vitor Freitas) #4

The field ID should be: {{ start_date.id_for_label }}, instead of {{ start_date.id_start_date }}.

Alternatively, you can also change the jQuery selector to:

$("input[name='start_date']").datetimepicker();

So you use the name instead of the ID.


(cix) #5

Hello Vitor,
What could be wrong, the calendar widget is not showing.


(Lúcio Henrique) #6

Did you import js and css required file?


(cix) #7

Hi Lucheol,
Yes, I imported it in my base.html