从上下文创建一组单选按钮 [英] Creating a set of radio buttons from a context
问题描述
我想将列表 y
作为上下文发送到模板.然后,对于 y
中的每个元素 x
,我想在模板中创建一个单选按钮.当我要处理提交的表单时,每个单选按钮应具有等于 x
的 value
属性,并且此单选按钮的标签也应设置为x
.
I want to send a list y
as a context to a template. Then, for each element x
in y
, I want to create a radio button in the template. Each radio button should have its value
attribute equal to x
for when I want to process the submitted form, and the label for this radio button should also be set to x
.
在视图中,用于将上下文发送到模板,我有:
In the view, for sending the context to the template, I have:
y = [0] * 10
for i in range(0, 10):
y[i] = # assign to some value
context = {'y': names}
return render(request, 'mytemplate.html', context)
然后在模板中,我尝试了一些尝试来根据需要显示这些单选按钮,但似乎没有任何效果.例如:
Then in the template, I've tried a few things to try to display these radio buttons as I want, but nothing seems to quite work. For example:
<form>
{% for x in y %}
<label><input type="radio" name="group1" value=x>x</label><br>
{% endfor %}
</form>
输出一组单选按钮,其标签仅是文本"x",而不是列表 y
中的值.需要做些什么不同的事情?
outputs a set of radio buttons whose labels are simply the text "x", rather than its value from the list y
. What needs to be done differently?
推荐答案
您应使用{{variable_name}}.像这样:
You should use {{ variable_name }}. Like this:
<form>
{% for x in y %}
<label><input type="radio" name="group1" value="{{ x }}">{{ x }}</label><br>
{% endfor %}
发生的事情是,您没有使用Django模板的sintax,而只是编写了一个有效的html标签,因此单选按钮中的x是
What happened is that you didn't use Django template sintax and just wrote a valid html label, hence the x in the radio buttons
这篇关于从上下文创建一组单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!