Django - change default presentation format of model date field

[亡魂溺海] 提交于 2020-01-31 21:16:02

问题


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?


回答1:


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




回答2:


use pynthon datetime:

from datetime import datetime

date = models.DateField(blank=False, default=datetime.now().strftime("%d.%m.%Y"))



回答3:


If what you are concerned about is how the date is displayed (output format); you can use a date filter, as explained here:

{{ obj.date|date:"d.m.Y"}} 

And here the Django docs.



来源:https://stackoverflow.com/questions/25204299/django-change-default-presentation-format-of-model-date-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!