Using Django Admin DatePicker in Custom Form
28 Jul 2016The Problem
How can I use Django admin date and time widgets in my custom view?
Django admin datepicker and time widget is no easier to implement than just using another third party javascript widget. But if you are insist, here you are.
Reference: Using Django time/date widgets in custom form It doesn’t seem work with latest Django (it’s Django 1.9 for now)
The solution
On your forms, change the widget to AdminDateWidget
and AdminTimeWidget
.
from django import forms
from django.contrib.admin import widgets
from .models import Event
class EventForm(forms.ModelForm):
class Meta:
model = Event
fields = ('id', 'title', 'description', 'date', 'start_time',
'end_time')
def __init__(self, *args, **kwargs):
super(EventForm, self).__init__(*args, **kwargs)
self.fields['date'].widget = widgets.AdminDateWidget()
self.fields['start_time'].widget = widgets.AdminTimeWidget()
self.fields['end_time'].widget = widgets.AdminTimeWidget()
- You need to include
{{ form.media }}
in your template. - The widgets need i18n and core JS but is not included in
{{ form.media }}
so you need manually include those. {{ form.media }}
will includeDateTimeShortcuts.js
which expect jQuery in django admin (django.JQuery) so you need to make alias to $
<script>
var django = django || {};
django.jQuery = $;
</script>
- You also need to include some django admin stylesheets so the calendar work nicely.
- You need add special class to your fields.
vDateField
for date widget andvTimeField
for time widget. I usedjango-widget-tweaks
to easy tweak that class on the template.
{% load widget_tweaks %}
{% block extra_header %}
<link rel="stylesheet" type="text/css" href="/static/admin/css/base.css"/>
<link rel="stylesheet" type="text/css" href="/static/admin/css/widgets.css"/>
<link rel="stylesheet" type="text/css" href="/static/admin/css/forms.css"/>
<link rel="stylesheet" type="text/css" href="/static/admin/css/global.css"/>
{% endblock %}
{% block content %}
<div class="form-group">
...
<div class="form-group">
{{ form.date.label_tag }}
{% render_field form.date class="vDateField" %}
{{ form.date.errors }}
</div>
<div class="form-group">
{{ form.start_time.label_tag }}
{% render_field form.start_time class="vTimeField" %}
{{ form.start_time.errors }}
</div>
</div>
{% endblock %}
{% block footer_js %}
<script>
var django = django || {};
django.jQuery = $;
</script>
<script type="text/javascript" src="/admin/jsi18n/"></script>
{{ formset.media }}
{% endblock %}
- Lastly, you need to manually wire i18n js to
django.views.i18n.javascript_catalog
(or null_javascript_catalog if you aren’t using I18N)
urlpatterns = [
...
url(r'^admin/jsi18n', 'django.views.i18n.javascript_catalog'),
]