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.
Method 1 : manual format rendering but fails datefield format validation
So best formating solution for you would be "."
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 :
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
The most important:
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
You can show date in template by means of
To display initial field value properly formatted, use
DateInput
widget. To customize validation, useinput_formats
keyword argument ofDateField
.Why do you need both
format
andinput_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.Subclass custom field like this: