如何解决Django views.py没有将dictionary值传递给html的问题



我在views.py中有一个字典值,并将其呈现到前端。当我在html中循环遍历字典时,只有一个值显示,而其他值则不显示。这可能有什么问题?

视图.py

def Student_Create(request):
form = Student_Model_Form(request.POST or None)
# get class names and days
classes = Create_Class.objects.all()
cls = {}
for i in classes:
cls[i] = {
'class_name': i.class_name,
'from_day': str(i.from_days),
'to_day': str(i.to_days),
'from_time': i.from_time.strftime("%H:%M:%S"),
'to_time': i.to_time.strftime("%H:%M:%S"),
}
print(cls)
template_name = 'genius/students_create.html'
context = {'form': form, 'classes': cls}
return render(request, template_name, context)

student.html

<div class="form-group">
<label for="select-class">Select Class</label>
<select class="custom-select" multiple name="select-class">
{% for i in classes%}
<option value="{{i.class_name}}">{{i.class_name}} : {{i.from_day}}-{{i.to_day}}</option>
{% endfor %}
</select>
</div>

最后的输出是这样的。

参见输出

非常感谢您的帮助。

而不是像上面那样创建dict。你可以views.py

def Student_Create(request):
form = Student_Model_Form(request.POST or None)
# get class names and days
classes = Create_Class.objects.values_list('class_name', 'from_days', 'to_days' ,'from_time', 'to_time', flat=True)
template_name = 'genius/students_create.html'
context = {'form': form, 'classes': classes}
return render(request, template_name, context)

您可以使用列表来存储数据:

...
cls = []  # Change from dict to list.
for i in classes:
cls.append({
'class_name': i.class_name,
'from_day': str(i.from_days),
'to_day': str(i.to_days),
'from_time': i.from_time.strftime("%H:%M:%S"),
'to_time': i.to_time.strftime("%H:%M:%S"),
})
...

最新更新