如何手动渲染表单字段并设置其初始值?
我正在尝试手动渲染表单的字段,以便我的设计师同事可以操作 HTML 中的输入元素,而不是在 Python 源代码中苦苦挣扎。
IE。而不是像这样声明表单字段......
{{ form.first_name }}
我实际上是这样做......
<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 %}
问题是似乎没有办法在第二种方法中获取字段的初始值。 {{ form.first_name }} 语句确实使用正确的初始值渲染输入元素,但不知怎的,当您想要手动呈现表单。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
关于这个问题,有一个有趣的长期存在的票证。注释中有用于实现模板过滤器的示例代码,它应该满足您的需要:
http://code。 djangoproject.com/ticket/10427
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
您必须使用
default_if_none
因为绑定字段的隐式值不会存储在data 中。
更多详情请点击此处You will have to use
default_if_none
because the implicit value of a bound field will not be stored indata.
More details here