-->

Django: How to format a DateField's date repre

2019-01-17 11:17发布

问题:

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

2009-10-03

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

03.10.2009

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

回答1:

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

Why do you need both format and input_formats?

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

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



回答2:

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

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

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).

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

..
..
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. 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')

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

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

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



回答3:

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:

You can show date in template by means of

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