Django - change default presentation format of model date field

user2216190 picture user2216190 · Aug 8, 2014 · Viewed 9.5k times · Source

I have a model with DateField, set like this :

date = models.DateField(blank=False, default=datetime.now)

each time I put that field data in a tamplate ({{obj.date}}) it shown in this format :

July 24, 2014

and I want to change that permanently to this format:

24.7.2014

also I have a search page where data can be searched by its date field - I want to be able to search in this format as well. How can I do that?

EDIT: I think it has somthing to do with the LANGUAGE_CODE = 'en-us' setting. when I change that it also changes the format of the date. how can it be overwrited?

Answer

mrcrgl picture mrcrgl · Aug 8, 2014

Django is using l10n to format numbers, dates etc. to local values. Changing your LANGUAGE_CODE is a good point and allows Django to load the correct environment.

In addition to this you need to configure the use of l10n via USE_L10N=True See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-USE_L10N

To enable a form field to localize input and output data simply use its localize argument:

class CashRegisterForm(forms.Form):
   product = forms.CharField()
   revenue = forms.DecimalField(max_digits=4, decimal_places=2, localize=True)

This works also fine for dates.

(from: https://docs.djangoproject.com/en/dev/topics/i18n/formatting/#locale-aware-input-in-forms)

edit: For the use in template you can just simple format dates via:

{% load l10n %}

{{ value|localize }}

or

{{ your_date|date:"SHORT_DATE_FORMAT" }}

second one is using the SHORT_DATE_FORMAT in settings.py

cheers, Marc