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.
我知道还有其他方法可以在django中分配初始值,但我需要在模板中分配值,因为该变量仅存在于模板中。
The way to do this with a normal html form would be this:
使用普通的html表单执行此操作的方法是:
{% 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 %}
However, I need to use a django form.
但是,我需要使用django表单。
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.
所以我的问题基本上是你如何去做上面的例子,而不是分配标签,分配一个值。
I've found a solution!
我找到了解决方案!
What I did was type the html manually as Daniel suggested and assigned the value that way.
我所做的是像Daniel建议的那样手动输入html,然后分配值。
For anyone who is wondering how I did it here is an example.
对于那些想知道我是怎么做的人来说,这是一个例子。
1 个解决方案
#1
3
In a nut shell you DON'T do this in HTML (unless you want to manually create the form as you described doing), you do it in Python.
在坚果壳中,你不要用HTML做这件事(除非你想按照你的描述手动创建表格),你用Python做。
in forms.py
you can set the initial
property to define the default value of the field.
在forms.py中,您可以设置初始属性以定义字段的默认值。
ex: name = forms.CharField(initial='class')
例如:name = forms.CharField(initial ='class')
or dynamically in views.py
you can use a dict
.
或者在views.py中动态地使用dict。
ex: f = CommentForm(initial={'name': 'instance'})
例如:f = CommentForm(initial = {'name':'instance'})
Extended reference: https://docs.djangoproject.com/en/1.10/ref/forms/api/#s-dynamic-initial-values
扩展参考:https://docs.djangoproject.com/en/1.10/ref/forms/api/#s-dynamic-initial-values
#1
3
In a nut shell you DON'T do this in HTML (unless you want to manually create the form as you described doing), you do it in Python.
在坚果壳中,你不要用HTML做这件事(除非你想按照你的描述手动创建表格),你用Python做。
in forms.py
you can set the initial
property to define the default value of the field.
在forms.py中,您可以设置初始属性以定义字段的默认值。
ex: name = forms.CharField(initial='class')
例如:name = forms.CharField(initial ='class')
or dynamically in views.py
you can use a dict
.
或者在views.py中动态地使用dict。
ex: f = CommentForm(initial={'name': 'instance'})
例如:f = CommentForm(initial = {'name':'instance'})
Extended reference: https://docs.djangoproject.com/en/1.10/ref/forms/api/#s-dynamic-initial-values
扩展参考:https://docs.djangoproject.com/en/1.10/ref/forms/api/#s-dynamic-initial-values