如何为模板中的Django表单字段分配值? [英] How to assign a value to a django form field in the template?
问题描述
我想知道如何在模板中为django表单字段分配值。
I was wondering how you can assign a value to a django form field in the template.
我知道还有其他方法可以在django中分配初始值,但是我需要在模板中分配值,因为变量仅存在于模板中。
I know that there is other ways to assign an initial value in django, but I need to assign the value in the template because the variable is only present in the template.
使用普通html格式执行此操作的方法是:
The way to do this with a normal html form would be this:
{% for thing in things %}
<p> {{ thing.content }} </p>
<!-- Reply form -->
<form>
<input type="hidden" name="replyingto" value="{{ thing.number }}">
<input type="text" label="Reply"></input>
</form>
{% endfor %}
但是,我需要使用Django表单。
However, I need to use a django form.
我也知道有一种方法可以为模板中的字段分配标签,例如:
I also know there is a way to assign a label to a field in the template, like this:
{{ form.non_field_errors }}
{{ form.field.errors }}
<label for="{{ form.field.id_for_label }}"> field </label>
{{ form.field }}
所以我的问题基本上是您将如何处理
So my question is basically how you would go about doing the example above but instead of assigning a label, assign a value.
我找到了解决方案!
p>
我所做的是手动输入html为 Daniel 建议并以这种方式分配值。
What I did was type the html manually as Daniel suggested and assigned the value that way.
对于任何想知道我在这里是如何做到的人来说,这是示例。
For anyone who is wondering how I did it here is an example.
推荐答案
您可以在Python中进行操作,然后可以在HTML表单或生成器中使用它
you do it in Python, which can then be available to the HTML form or generator
在 forms.py
,您可以设置 initial
属性来定义字段的默认值。
in forms.py
you can set the initial
property to define the default value of the field.
ex : name = form.CharField(initial ='class')
或动态地在中views.py
您可以使用 dict
。
or dynamically in views.py
you can use a dict
.
例如: f = CommentForm(initial = {'name':'instance'})
一旦在表格中可用
实例,您可以在HTML中使用 {{form.field.value}}
或使用生成器自动使用
Once available within the form
instance you can use {{ form.field.value }}
in your HTML or automatically with a generator
扩展参考: https:/ /docs.djangoproject.com/en/1.10/ref/forms/api/#s-dynamic-initial-values
这篇关于如何为模板中的Django表单字段分配值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!