[Answered ]-Django Forms forms.DateInput / forms.DateField: formatting inconsistency between {{ form.datefield }} and {{ form.datefield.value }} in template code

2đź‘Ť

âś…

Yes, there is a difference between including a field instance or the field instance’s field.value in the template.

When you render a field instance in the template, it’s widget’s Widget.render method is called, and as a result, the Widget.format_value method is called.

This last method actually renders the python date object into a string using the localize_input helper. Here’s the relevant part of that function:

def localize_input(value, default=None):
    # ...
    elif isinstance(value, datetime.date):
        value = datetime_safe.new_date(value)
        format = force_str(default or get_format('DATE_INPUT_FORMATS')[0])
        return value.strftime(format)

As seen above, the format you specify (or the first value in DATE_INPUT_FORMATS) is used.

However, when you access the field.value attribute, you actually get the “raw” python date value (despite the misleading documentation). When the template evaluates the variable node, according to your example it uses your DATE_FORMAT setting, as the docs mention:

The default formatting to use for displaying date fields in any part of the system

If you want to render the value in a different format, you can do so easily with the date template filter; like so:

{{form.birth_date.value|date:"%Y-%m-%d"}} == {{form.birth_date}}

Or change the system wide default by updating the setting:

DATE_FORMAT = "%Y-%m-%d"
👤tutuDajuju

Leave a comment