str
str

Reputation: 44979

Change DateInput widget's format to SHORT_DATE_FORMAT

I'm trying to set the format of a DateInput to SHORT_DATE_FORMAT. However, the following code does not work work.

forms.py

from django.conf.global_settings import SHORT_DATE_FORMAT

class EventForm(ModelForm):
    # ...
    startDate = forms.DateField(
        widget=forms.DateInput(
            format=SHORT_DATE_FORMAT
        )
    )

In the views.py, an example entry is read from the database and a form is created using form = EventForm(instance=event1). The template then shows that widget using {{form.startDate}}. The input shows up correctly, only it's value is not a date but just "m/d/Y".

It would work if I'd set format='%m/%d/%Y', however, that defeats the purpose of the locale-aware SHORT_DATE_FORMAT. How can I properly solve that?

Upvotes: 3

Views: 807

Answers (1)

str
str

Reputation: 44979

A possible solution is to overwrite the DateInput widget as follows.

from django.template.defaultfilters import date

class ShortFormatDateInput(DateInput):

    def __init__(self, attrs=None):
        super(DateInput, self).__init__(attrs)

    def _format_value(self, value):
        return date(value, formats.get_format("SHORT_DATE_FORMAT"))

It overwrites the super constructor so that the date format cannot be changed manually anymore. Instead I'd like to show the date as defined in SHORT_DATE_FORMAT. To do that, the _format_value method can be overwritten to reuse the date method defined django.templates.

Upvotes: 1

Related Questions