[Django]-Django admin datetime widget (calendar) in a custom form

0👍

I think the easiest way is not to use the widget from django.contrib.admin.widgets but rather a third party widget such as the Datepicker from jQuery UI.

All you have to do is to include jQuery UI in your template and add this script

<script>
  $(function() {
    $( ".date_picker" ).datepicker();
  });
</script>

Where .date_picker is the name of the class of the form input related to the date field of your Reservation model.

In order for Django to add this class='date_picker' to the generated form input related to date, you have to slightly modify your ModelForm. More specifically,

from django import forms
from booking.models import Reservation

class ReservationForm(forms.ModelForm):
    class Meta:
        model = Reservation
        exclude = ['user']
        widgets = {
            'date' : forms.DateInput(attrs={'class' : 'date_picker'})
        }

This will have the effect of rendering <input type='text' ... class='date_picker' /> when you call {{ form.as_p }} in your template, and jQuery UI does the rest.

By the way, a small improvement to your models.py would be to use python’s list comprehension. Namely

FIELDNUM = (('1', '1'), ('2', '2'), ('3', '3'),
        ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ('8', '8'),
        ('9', '9'), ('10', '10'))

is equivalent to

FIELDNUM = [(str(i), str(i)) for i in range(1,11)]

Leave a comment