Formatting Dates in Django

By default Django date fields populate with values in the yyyy-mm-dd format. Such as 2017-11-26. This isn't a format that many people actually use. The real problem comes if you want to use a date picker with the date field in your form. If the format used by the date picker, doesn't match the format used by the Django field, you'll get all kinds of issues.

Fortunately there is a really easy fix: set the date format you want in the form itself. As an example let's say we have a model for Appointments that has an appointment_date field.

from django import forms
from models import Appointments

class AppointmentForm(forms.ModelForm):

    class Meta:
        model = Appointments
        fields = ['appointment_date', 'name', 'type_of_appointment']

    appointment_date = forms.DateField(
        input_formats=('%m/%d/%Y', )

The widget attribute sets the display format for the field. The input_formats attribute lets you define the acceptable formats for date input. You can use all the standard Python string formatting options. You should match this to the format used by your date picker of choice.

While you are at it this can be a convenient place to add a class or two to the HTML so that your date picker can attach itself to your date fields. You'll place the code in the widget, since it defines the display on the page.

Something like this:

appointment_date = forms.DateField(
        widget=forms.DateInput(format='%m/%d/%Y', attrs={'class': 'datepicker'}),
        input_formats=('%m/%d/%Y', )

Read more about Django widgets here.


Comments powered by Disqus