Gilang Chandrasa Thoughts, stories, and ideas

Using Django Admin DatePicker in Custom Form

The 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()
<script>
    var django = django || {};
    django.jQuery = $;
</script>
{% 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 %}
urlpatterns = [
    ...
    url(r'^admin/jsi18n', 'django.views.i18n.javascript_catalog'),
]