Django:如何格式化DateField的日期表示?

时间:2022-10-04 19:13:45

I have a form with a DateField. The existing date value is formatted to render like this:

我有一个带有DateField的表单。现有日期值的格式设置为如下所示:

2009-10-03

2009-10-03

How can I format that so that it look like this:

我该如何格式化它,使它看起来像这样:

03.10.2009

2009年3月10日

I found a widget which renders it like this, but validation doesn't allow the values I enter then.

我找到了一个像这样呈现它的小部件,但验证不允许我输入的值。

4 个解决方案

#1


36  

To display initial field value properly formatted, use DateInput widget. To customize validation, use input_formats keyword argument of DateField.

要显示格式正确的初始字段值,请使用DateInput小部件。要自定义验证,请使用DateField的input_formats关键字参数。

Why do you need both format and input_formats?

为什么需要format和input_formats?

format - The format in which this field’s initial value will be displayed. See here.

format - 将显示此字段的初始值的格式。看这里。

input_formats - A list of formats used to attempt to convert a string to a valid datetime.date object. See here.

input_formats - 用于尝试将字符串转换为有效datetime.date对象的格式列表。看这里。

#2


11  

Method 1 : manual format rendering but fails datefield format validation

So best formating solution for you would be "."

所以最好的格式化解决方案就是“。”

{{field.value.day|stringformat:"02d"}}.{{field.value.month|stringformat:"02d"}}.{{field.value.year}}

to get 24.05.2010

得到24.05.2010

I added stringformat:"02d" to not get 25.5.2010 as output value.

我添加了stringformat:“02d”以得不到25.5.2010作为输出值。

I post the full code of a field to get an idea :

我发布了一个字段的完整代码来获得一个想法:

<input class="form-control" data-inputmask="'mask':'99.99.9999'" data-toggle="masked"  name="{{field.html_name}}" placeholder="{{ field.label }}" {% if field.field.required %}required=""{% endif%} type="text" value="{{field.value.day|stringformat:"02d"}}.{{field.value.month|stringformat:"02d"}}.{{field.value.year}}" " >

I mainly used this formatting for the date value on an existing instance of an update (model) form (UpdateView class).

我主要在更新(模型)表单(UpdateView类)的现有实例上使用此格式作为日期值。

This solution may fail when submitting the update form if it will not satisfy the format

如果提交更新表单不符合格式,则此解决方案可能会失败

Method 2 : (Better) automatize field value formatting + correct validation using settings

It's done by adding custom local settings to settings.py file : The most important part is the DATE_INPUT_FORMATS tuple

这是通过向settings.py文件添加自定义本地设置来完成的:最重要的部分是DATE_INPUT_FORMATS元组

..
..
USE_L10N = True
..

DATE_INPUT_FORMATS = (
    '%d.%m.%Y', '%d.%m.%Y', '%d.%m.%y',  # '25.10.2006', '25.10.2006', '25.10.06'
    '%d-%m-%Y', '%d/%m/%Y', '%d/%m/%y',  # '25-10-2006', '25/10/2006', '25/10/06'
    '%d %b %Y',  # '25 Oct 2006', 
    '%d %B %Y',  # '25 October 2006', 
)

DATE_FORMAT = 'j F Y'
TIME_FORMAT = 'H:i'
DATETIME_FORMAT = 'j F Y H:i'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j F'
SHORT_DATE_FORMAT = 'j N Y'
SHORT_DATETIME_FORMAT = 'j N Y H:i'
FIRST_DAY_OF_WEEK = 1

The most important:

最重要的:

  1. The validation of datefields is done on insert and update with all formats present in DATE_INPUT_FORMATS tuple
  2. 日期字段的验证是在插入和更新时完成的,所有格式都存在于DATE_INPUT_FORMATS元组中
  3. On updateView, the date field will be rendered using the first format of DATE_INPUT_FORMATS tuple (i mean using DATE_INPUT_FORMATS[0] == '%d.%m.%Y')
  4. 在updateView上,日期字段将使用DATE_INPUT_FORMATS元组的第一种格式呈现(我的意思是使用DATE_INPUT_FORMATS [0] =='%d。%m。%Y')

So the choice of the first element is important in this tuple as it defines the formating of existing value of datefield on update forms

因此,第一个元素的选择在此元组中很重要,因为它定义了更新表单上datefield的现有值的格式

You can apply javascript validation on UpdateViews using this first format too.

您也可以使用第一种格式在UpdateViews上应用javascript验证。

Tested on django 1.6 and 1.7 , don't know for previous versions

在django 1.6和1.7上测试过,不知道以前的版本

#3


6  

Subclass custom field like this:

子类自定义字段如下:

class CustomDateField(forms.DateField):
  def __init__(self, *args, **kwargs):
    kwargs.setdefault('input_formats', ("%d.%m.%Y",))
    super(CustomDateField, self).__init__(*args, **kwargs)

#4


4  

You can show date in template by means of

您可以通过以下方式在模板中显示日期

{{ your_object.date_field.day }}.{{ your_object.date_field.month }}.{{ your_object.date_field.year }}

#1


36  

To display initial field value properly formatted, use DateInput widget. To customize validation, use input_formats keyword argument of DateField.

要显示格式正确的初始字段值,请使用DateInput小部件。要自定义验证,请使用DateField的input_formats关键字参数。

Why do you need both format and input_formats?

为什么需要format和input_formats?

format - The format in which this field’s initial value will be displayed. See here.

format - 将显示此字段的初始值的格式。看这里。

input_formats - A list of formats used to attempt to convert a string to a valid datetime.date object. See here.

input_formats - 用于尝试将字符串转换为有效datetime.date对象的格式列表。看这里。

#2


11  

Method 1 : manual format rendering but fails datefield format validation

So best formating solution for you would be "."

所以最好的格式化解决方案就是“。”

{{field.value.day|stringformat:"02d"}}.{{field.value.month|stringformat:"02d"}}.{{field.value.year}}

to get 24.05.2010

得到24.05.2010

I added stringformat:"02d" to not get 25.5.2010 as output value.

我添加了stringformat:“02d”以得不到25.5.2010作为输出值。

I post the full code of a field to get an idea :

我发布了一个字段的完整代码来获得一个想法:

<input class="form-control" data-inputmask="'mask':'99.99.9999'" data-toggle="masked"  name="{{field.html_name}}" placeholder="{{ field.label }}" {% if field.field.required %}required=""{% endif%} type="text" value="{{field.value.day|stringformat:"02d"}}.{{field.value.month|stringformat:"02d"}}.{{field.value.year}}" " >

I mainly used this formatting for the date value on an existing instance of an update (model) form (UpdateView class).

我主要在更新(模型)表单(UpdateView类)的现有实例上使用此格式作为日期值。

This solution may fail when submitting the update form if it will not satisfy the format

如果提交更新表单不符合格式,则此解决方案可能会失败

Method 2 : (Better) automatize field value formatting + correct validation using settings

It's done by adding custom local settings to settings.py file : The most important part is the DATE_INPUT_FORMATS tuple

这是通过向settings.py文件添加自定义本地设置来完成的:最重要的部分是DATE_INPUT_FORMATS元组

..
..
USE_L10N = True
..

DATE_INPUT_FORMATS = (
    '%d.%m.%Y', '%d.%m.%Y', '%d.%m.%y',  # '25.10.2006', '25.10.2006', '25.10.06'
    '%d-%m-%Y', '%d/%m/%Y', '%d/%m/%y',  # '25-10-2006', '25/10/2006', '25/10/06'
    '%d %b %Y',  # '25 Oct 2006', 
    '%d %B %Y',  # '25 October 2006', 
)

DATE_FORMAT = 'j F Y'
TIME_FORMAT = 'H:i'
DATETIME_FORMAT = 'j F Y H:i'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j F'
SHORT_DATE_FORMAT = 'j N Y'
SHORT_DATETIME_FORMAT = 'j N Y H:i'
FIRST_DAY_OF_WEEK = 1

The most important:

最重要的:

  1. The validation of datefields is done on insert and update with all formats present in DATE_INPUT_FORMATS tuple
  2. 日期字段的验证是在插入和更新时完成的,所有格式都存在于DATE_INPUT_FORMATS元组中
  3. On updateView, the date field will be rendered using the first format of DATE_INPUT_FORMATS tuple (i mean using DATE_INPUT_FORMATS[0] == '%d.%m.%Y')
  4. 在updateView上,日期字段将使用DATE_INPUT_FORMATS元组的第一种格式呈现(我的意思是使用DATE_INPUT_FORMATS [0] =='%d。%m。%Y')

So the choice of the first element is important in this tuple as it defines the formating of existing value of datefield on update forms

因此,第一个元素的选择在此元组中很重要,因为它定义了更新表单上datefield的现有值的格式

You can apply javascript validation on UpdateViews using this first format too.

您也可以使用第一种格式在UpdateViews上应用javascript验证。

Tested on django 1.6 and 1.7 , don't know for previous versions

在django 1.6和1.7上测试过,不知道以前的版本

#3


6  

Subclass custom field like this:

子类自定义字段如下:

class CustomDateField(forms.DateField):
  def __init__(self, *args, **kwargs):
    kwargs.setdefault('input_formats', ("%d.%m.%Y",))
    super(CustomDateField, self).__init__(*args, **kwargs)

#4


4  

You can show date in template by means of

您可以通过以下方式在模板中显示日期

{{ your_object.date_field.day }}.{{ your_object.date_field.month }}.{{ your_object.date_field.year }}