Reputation: 13335
To get some more control over my input fields, I try to "copy" the function that generates input fields in the template
I use a ModelForm and I want to change
...
{{ form.name }}
...
into something like
...
<input id="{{ form.name.auto_id }}" type="text" name="{{ form.name.name }}" maxlength="{{ form.name.**get_max_length** }}" value="{{ form.name.**get_value_or_initial_value** }}"/>
...
Most of that works already, except maxlength and value.
maxlength
I read
but I still don't get it right...
value
The answer to this question (How can you manually render a form field with its initial value set?) points to a ticket which is fixed already. Still name.value
would print "None" if there is no value present. Am I meant to catch value="None"
manually or is there a better solution meanwhile?
[edit]
value seems to work like that
{{ form.name.value|default_if_none:"" }}
(from Display value of a django form field in a template?)
Upvotes: 0
Views: 638
Reputation: 1380
You can get the max_length attribute from the widget. For the initial value, you only need to access the value attribute, there is already an initial or submitted value. All initial values passed to form class are held in form.initial, but you probably don't need to check these values:.
<input id="{{ form.name.auto_id }}" type="text" name="{{ form.name.name }}" maxlength="{{ form.name.field.widget.attrs.max_length }}" value="{% if form.name.value %}{{ form.name.value }}{% endif %}"/>
Upvotes: 2