我正在尝试使用Django,Jinja2和PostgreSQL创建一个测验应用程序。我想给问题编号,但我不知道该怎么做,因为python在for循环中不使用计数器(例如,在练习中进行锻炼-这里没有for循环)
我尝试更改for循环
(for exercise in exercises)
因此它有一个计数器
(for x in myrange)
,然后在views.py中将myrange定义为range(1,len(exercitii + 1)) 但是之后,我不知道如何访问Jinja模板中的元素。 我尝试使用
访问练习{exercitii.x-1.intrebare}}
但是没有用。
html模板
{% extends 'base.html' %}
{% load static %}
{% block content %}
</div>
<div id="middle-section" class="container-fluid container-fluid-margin">
<div class="content-quiz">
<form action="{% url 'exercitiu' lectii.id %}" method="POST" id="quiz">
{% for exercitiu in exercitii %}
<div class="row content-block">
<div class="col-lg-10 text-card">
{% csrf_token %}
<div class="card card-custom">
<div class="card-body">
<h5 class="card-title">{{exercitiu.id}} - {{exercitiu.intrebare}}</h5>
<div class="card-text">
<input type="radio" name="question-{{exercitiu.id}}-answers" id="question-{{exercitiu.id}}-answers-A" value="A" />
<label for="question-{{exercitiu.id}}-answers-A">A) {{exercitiu.variante.0}} </label>
</div>
<div class="card-text">
<input type="radio" name="question-{{exercitiu.id}}-answers" id="question-{{exercitiu.id}}-answers-B" value="B" />
<label for="question-{{exercitiu.id}}-answers-B">B) {{exercitiu.variante.1}} </label>
</div>
<div class="card-text">
<input type="radio" name="question-{{exercitiu.id}}-answers" id="question-{{exercitiu.id}}-answers-C" value="C" />
<label for="question-{{exercitiu.id}}-answers-C">C) {{exercitiu.variante.2}} </label>
</div>
<div class="card-text">
<input type="radio" name="question-{{exercitiu.id}}-answers" id="question-{{exercitiu.id}}-answers-D" value="D" />
<label for="question-{{exercitiu.id}}-answers-D">D) {{exercitiu.variante.3}} </label>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
<input type="submit" value="Trimite" class="btn btn-secondary btn-block btn-login-custom" style="margin-bottom: 2rem;">
</div>
</div>
{% endblock %}
views.py
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from .models import Exercises
from .models import Lectie
def exercitii(req):
lectii = Lectie.objects.all().order_by("id")
context = {
'lectii': lectii
}
return render(req, '../templates/pagini/exercitii-selector.html', context)
def exercitiu(req, lectie_id):
lectii = get_object_or_404(Lectie, pk=lectie_id)
exercitiiObj = Exercises.objects.filter(idLectie=lectie_id)
context = {
'lectii': lectii,
'exercitii': exercitiiObj
}
return render(req, '../templates/pagini/exercitii.html', context)
(lectie =课,lectii =课,exercitii =练习)
那么我如何在模板中编号来自exercitiiObj的问题?现在,输出是来自数据库的练习ID,这完全没有帮助。 谢谢。