Skip to content

Instantly share code, notes, and snippets.

@maraujop
Last active October 9, 2021 19:56
Show Gist options
  • Save maraujop/2812529 to your computer and use it in GitHub Desktop.
Save maraujop/2812529 to your computer and use it in GitHub Desktop.
Datepicker template for django-crispy-forms
{% load crispy_forms_field %}
<div id="div_{{ field.auto_id }}" class="control-group{% if form_show_errors and field.errors %} error{% endif %} {% if field.field.widget.attrs.class %} {{ field.field.widget.attrs.class }}{% endif %}">
{% if field.label %}
<label for="{{ field.id_for_label }}" class="control-label {% if field.field.required %}requiredField{% endif %}">
{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
</label>
{% endif %}
<div class="controls">
<div class="input-append">
{% crispy_field field %}
<span class="add-on {% if active %}active{% endif %}">{{ crispy_appended_text|safe }}</span>
</div>
{% include 'bootstrap/layout/help_text_and_errors.html' %}
</div>
</div>
<!--
To be used with bootstrap-datepicker and Django DateField.
http://www.eyecon.ro/bootstrap-datepicker/
In your layout do: `Field('field_name', template='date.html')`
Make sure date.html is in your templates path. You could build a custom layout object inheriting from `Field` named `DateField` that could get parameters passed for `data-date` and `data-date-format` for example.
-->
@EugeneDae
Copy link

Sorry, but why not just run a tiny piece of js code,

$(document).ready(function() {
    $('.dateinput').datepicker({ format: "yyyy/mm/dd" });
}); 

to automatically append the datepicker to all of the DateField's? If one doesn't want to append it to all of the fields, they could replace .dateinput with something like .datepicker and then reference it using crispy-forms like Field(css_class='datepicker').

@maraujop
Copy link
Author

That's an option, I did this gist for a user trying to create a template for rendering HTML for datepicker. Alternatively you could use JS as you say, which is most likely a better option.

@ganeshragav
Copy link

EugeneDae,

Could you provide a gist or assistance in adding your method in form as well as in html. I would like to use your method in my code. This will be of much help.

@sidestrand
Copy link

I've been struggling with this for a year now! Where should I put EugeneDae's js code? Does it go in forms.py, or on each html page which needs a datetimepicker?

@shayneoneill
Copy link

It goes in a file called date.html with the other templates , then in the field you add template='date.html' in the form helper layout section

@addisonklinke
Copy link

I get an error when trying to use Field(..., template='date.html') in my forms.py

VariableDoesNotExist at /events/create
Failed lookup for key [field]

Generated by line 13 of your template

{% crispy_field field %}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment