How can you manually render a form field with its initial value set?

大城市里の小女人 提交于 2020-01-05 05:54:34

问题


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



来源:https://stackoverflow.com/questions/3929903/how-can-you-manually-render-a-form-field-with-its-initial-value-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!