I’m rendering form fields manually in my Django templates. It works fine but I’ve hit a problem with a custom Field’s format
parameter not being used when rendering a field’s value
attribute.
To render an <input type="datetime-local">
I have this custom Input and Field:
from django import forms
class DateTimeLocalInput(forms.DateTimeInput):
input_type = "datetime-local"
class DateTimeLocalField(forms.DateTimeField):
input_formats = [
"%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M:%S.%f", "%Y-%m-%dT%H:%M"
]
widget = DateTimeLocalInput(format="%Y-%m-%dT%H:%M")
Then I use this in a model form, for a field DateTimeField
model attribute like this:
class MyForm(forms.ModelForm):
fieldname = DateTimeLocalField(label="My field")
In a template if I render a field by doing {{ form.fieldname }}
then it outputs as I’d expect, using the format
parameter in the last line, above. e.g.:
<input type="datetime-local" name="fieldname" value="2023-11-02T22:30" id="id_fieldname">
But if I render a field’s value attribute manually like this:
<input ... value="{{ form.fieldname.value|default_if_none:""|stringformat:'s' }}">
Then it comes out like this:
<input ... value="2023-11-02 22:30:35">
You can see that the Field’s format
is ignored: the value is output with no T
in the middle, and with the seconds included. This is a problem in Safari, which refuses to accept that as a valid format.
I can’t see how to get round this. In a widget’s context data, value
is set as self.format_value(value)
(seen here on GitHub), but I think that’s not happening when just using {{ form.fieldname.value }}
.