0

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

Community
  • 1
  • 1
speendo
  • 13,045
  • 22
  • 71
  • 107

1 Answers1

2

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 %}"/>
Bruce
  • 1,380
  • 2
  • 13
  • 17
  • thanks! `value` seems to work (I also found a shortcut - see the edit in my question), however, I cannot get `max_length` to work like this. did you try it out? – speendo Aug 24 '14 at 12:27
  • 1
    Sorry, I forgot the field attribute, it is fixed now. BoundField has no direct access to the widget. – Bruce Aug 24 '14 at 18:56