How can you manually render a form field with its

2019-08-05 07:21发布

问题:

I'm trying to render a form's fields manually so that my designer colleagues could manipulate the input elements within the HTML instead of struggling in Python source.

ie. Instead of declaring form fields like this...

            {{ form.first_name }}   

.. I actually do ...

            <label for="id_first_name">Your name:</label>
            <input type="text" value="{{  form.first_name.somehow_get_initial_value_here }}" name="first_name" id="id_first_name" class="blabla" maxlength="30" >
            {% if form.first_name.errors %}<span>*** {{ form.first_name.errors|join:", " }}</span>{% endif %}

Problem is that there seems to be no way to get the initial value of the field in the second method. {{ form.first_name }} statement does render the input element with the proper initial value but somehow there is nothing like {{ form.first_name.initial_value }} field when you want to render the form manually.

回答1:

There is an interesting long standing ticket about this very issue. There is sample code to implement a template filter in the comments that should do what you need:

http://code.djangoproject.com/ticket/10427



回答2:

<input value="{{form.name.data|default_if_none:'my_defaut_value'}}" ... />

You will have to use default_if_none because the implicit value of a bound field will not be stored in data. More details here