英文:
Django - get value from html select options that have been generated in a loop
问题
我有一个HTML页面,在页面上设置了一个循环来列出乐队的名字。我还有一个选择框,让用户对他们看过的乐队进行评分。问题是,因为每个选择框选项都是在我的循环中生成的,我不知道如何在我的views.py文件中访问每个评分。请帮忙?
HTML代码
{% for band in thursday_apex %}
<li> {{ band.band_name }}
{{ }}
<select name="thursday_apex">
<option value="0">没看过</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</li>
{% endfor %}
英文:
i have a html page where i have set up a loop to list band names on a page. I also have a select option box so users can rate bands they have seen. Problem is because each of the select options is generated in my loop i don't know how i'm going to access each rating back in my views.py file. Please help?
html code
{% for band in thursday_apex %}
<li> {{ band.band_name }}
{{ }}
<select name="thursday_apex">
<option value="0">Didn't watch</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</li>
{% endfor %}
答案1
得分: 0
你在for循环中对每个迭代的数据都使用了相同的name
属性,要访问每个select
元素的value,需要像这样操作:
你的HTML:
{% for band in thursday_apex %}
<li>{{ band.band_name }}
<select name="thursday_apex_{{ band.id }}">
// 选项
</select>
</li>
{% endfor %}
你的views.py:
def function(request):
thursday_apex = YOUR_BAND_CLASS.objects.all()
my_list = []
if request.method == 'POST':
for item in thursday_apex:
select_value = request.POST.get('thursday_apex_' + str(item.id))
if select_value:
my_list.append({item.id: select_value})
print(my_list)
现在,你已经将所有select
的值存储在变量my_list中。
英文:
you are using the same name
attribute for each iterated data in for loop, to access the value of each select
element you need to do it like this:
your html:
{% for band in thursday_apex %}
<li> {{ band.band_name }}
<select name="thursday_apex_{{band.id}}">
// options
</select>
</li>
{% endfor %}
your views.py:
def function(request):
thursday_apex = YOUR_BAND_CLASS.objects.all()
list = []
if request.method == 'POST':
for item in thursday_apex:
select_value = request.POST.get('thursday_apex_' + str(item.id))
if select_value:
list.append({item.id: select_value})
print(list)
now you have all the select
values inside the variable list
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论