简体   繁体   English

如何手动呈现其初始值设置的表单字段?

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

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. 我正在尝试手动渲染表单的字段,以便我的设计人员可以操作HTML中的输入元素,而不是在Python源代码中挣扎。

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. {{form.first_name}}语句确实使用正确的初始值呈现输入元素,但是当您想要手动呈现表单时,某种程度上没有像{{form.first_name.initial_value}}字段那样的内容。

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 http://code.djangoproject.com/ticket/10427

<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. 您必须使用default_if_none因为绑定字段的隐式值不会存储在data. More details here 更多细节在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM