简体   繁体   English

Django - 更改模型日期字段的默认显示格式

[英]Django - change default presentation format of model date field

I have a model with DateField, set like this :我有一个带有 DateField 的模型,设置如下:

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 :每次我将该字段数据放入模板 ( {{obj.date}} ) 时,它都以这种格式显示:

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.编辑:我认为这与LANGUAGE_CODE = 'en-us'设置有关。 when I change that it also changes the format of the date.当我更改它时,它也会更改日期的格式。 how can it be overwrited?它怎么能被覆盖?

Django is using l10n to format numbers, dates etc. to local values. Django 使用 l10n 将数字、日期等格式化为本地值。 Changing your LANGUAGE_CODE is a good point and allows Django to load the correct environment.更改您的 LANGUAGE_CODE 是一个好点,它允许 Django 加载正确的环境。

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除此之外,您还需要通过 USE_L10N=True 配置 l10n 的使用,请参阅: 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:要启用表单字段来本地化输入和输出数据,只需使用其 localize 参数:

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 ) (来自: 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第二个是在 settings.py 中使用 SHORT_DATE_FORMAT

cheers, Marc干杯,马克

use pynthon datetime:使用 Pynthon 日期时间:

from datetime import datetime

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

If what you are concerned about is how the date is displayed (output format);如果您关心的是日期的显示方式(输出格式); you can use a date filter, as explained here :您可以使用date过滤器,为解释在这里

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

And here the Django docs .这里是Django 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM