Django-更改模型日期字段的默认表示格式 [英] Django - change default presentation format of model date field

查看:644
本文介绍了Django-更改模型日期字段的默认表示格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有DateField的模型,设置如下:

I have a model with DateField, set like this :

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

每次我将字段数据放在模板中( {{obj.date}} )以这种格式显示:

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?

编辑:我认为这与 LANGUAGE_CODE有关系= zh-cn 设置。当我更改时,它也会更改日期的格式。

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?

推荐答案

Django正在使用l10n将数字,日期等格式化为本地值。更改您的LANGUAGE_CODE是一个不错的选择,并且允许Django加载正确的环境。

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.

此外,您还需要通过USE_L10N = True
配置l10n的使用,请参见: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-USE_L10N

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

要使表单字段能够本地化输入和输出数据,只需使用其localize参数即可:

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)

对日期也有效。

(来自: 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 }}

{{ your_date|date:"SHORT_DATE_FORMAT" }}

第二个人正在settings.py

second one is using the SHORT_DATE_FORMAT in settings.py

干杯,马克

这篇关于Django-更改模型日期字段的默认表示格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆