Django如何从数据库中获取ID并显示在HTML中 [英] Django how to get id from the database and show in the html
本文介绍了Django如何从数据库中获取ID并显示在HTML中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的views.py:
this is my views.py:
def gradescales(request):
grade = list(gradeScalesSetting.objects.all()) # < DB hit once
gradeScalesSettings = gradeScalesSetting.objects.all()
rounding = []
configuration = []
for i in grade:
if i.Rounding not in rounding:
rounding.append(i.Rounding)
if i.Configuration not in configuration:
configuration.append(i.Configuration)
return render(request, 'Homepage/gradescale.html', {"rounding": rounding, "configuration": configuration,"gradeScalesSetting":gradeScalesSettings})
我使用此代码是因为我不想使用distinct(),但是我在获取其ID时遇到了麻烦.
i use this code because i dont want to use distinct(), but im getting trouble in getting their id.
这是我的模板
<select name="gradescale" id="gradescale" onchange="summary(this.value)" required="required" >
{% for r in configuration %}
<option value="{{r}}">{{r}}</option>
{% endfor %}
</select>
这是结果:
我只希望我的 中的值是我选择的列表的ID
i just want that in my the value is the id of what list i selected
这是我的数据库
更新我的尝试
<select name="gradescale" id="gradescale" onchange="summary(this.value)" required="required" >
{% for r in configuration %}
<option value="{{r}}">{{r.id}}</option>
{% endfor %}
</select>
这是它的样子
另一个更新这是更新views.py
Another Update this is the update views.py
for i in grade:
if i.Rounding not in rounding:
rounding.append(i)
if i.Configuration not in configuration:
configuration.append(i)
更新html
<select name="gradescale" id="gradescale" onchange="summary(this.value)" required="required" >
{% for r in configuration %}
<option value="{{r}}">{{r.id}}</option>
{% endfor %}
</select>
它是什么样子
推荐答案
您需要更改添加到该列表的方式:
You need to change the way you are appending to that list:
for i in grade:
if i.Rounding not in rounding:
rounding.append(i)
if i.Configuration not in configuration:
configuration.append(i)
在您的模板中:
<select name="gradescale" id="gradescale" onchange="summary(this.value)" required="required" >
{% for r in configuration %}
<option value="{{r.id}}">{{r}}</option>
{% endfor %}
</select>
这篇关于Django如何从数据库中获取ID并显示在HTML中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文