python - Django 表单 - 需要一个显示一组问题的表单,每个问题都有一个可能的答案列表
问题描述
我有以下三个模型:
models.py
class Exam(models.Model):
lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name="exams")
passing_grade = models.IntegerField(default=85)
must_pass = models.BooleanField(default=True)
to_next_lesson = models.BooleanField(default=True)
display_order = models.IntegerField(default=1)
class ExamQuestion(models.Model):
exam = models.ForeignKey(Exam, on_delete=models.CASCADE, related_name="questions")
text = models.CharField('Question', max_length=255)
class ExamAnswer(models.Model):
question = models.ForeignKey(ExamQuestion, on_delete=models.CASCADE, related_name="answers")
text = models.CharField('Answer', max_length=255)
is_correct = models.BooleanField('Correct answer', default=False)
我需要的表格会在考试中呈现每个问题,大致如下(抱歉无法显示有问题的呈现 html:
<form>
<div>
"Quality" is one our core values<br />
<input type="radio"/> True <br />
<input type="radio"/> False
</div>
<div>
What should you do if you see an employee stealing?<br />
<input type="radio"/> Report it to your manager<br />
<input type="radio"/> Call the police<br />
<input type="radio"/> Confront the employee<br />
</div>
<div>
<input type="submit">
</div>
</form>
忽略不完整且可能愚蠢的 HTML(此处显示概念的基本框架)如何让 Django 表单语言输出每个单独的问题,并在其下方提供多个答案?
注意:问题的数量是可变的,有些考试可能有 3 个问题,有些可能有 5 或 6 个。每个问题的答案数量也是可变的,有些问题可能有两个答案 - 通常是对或错,其他可能有四个或五个答案(现在每个问题只有一个正确答案,所以它总是使用单选按钮)
视图中的查询将发送考试的 pk,并从 ExamQuestion 和 ExamAnswer 表中提取适当的文本条目。
我可以将问题和答案放入模板所需的任何查询集、列表或字典中,但我无法弄清楚如何让它们在模板中正确显示。
解决方案
在 Django 表单中,您只需:
STEALING= [
('Report it to your manage', 'Report it to your manage'),
('Call the police', 'Call the police'),
('Confront the employee', 'Confront the employee')
]
class UserForm(forms.Form):
your_form_field_name = forms.CharField(label='What should you do?', widget=forms.Select(choices=STEALING))
推荐阅读
- angular - WebAPI + Angular项目上的AzureAd令牌刷新CORS错误
- html - 如何在 DataTable 中创建带有填充数据的表格的表格?
- java - 根据用户输入以 ASCII 艺术风格绘制心形
- scenekit - 在scenekit中对象到其他对象的投影轮廓
- photoshop - Photoshop:打开时将 jpeg 转换为 16 位的脚本
- jenkins - 詹金斯管道切割日志
- python - 使用python pandas过滤/迭代列中的每个项目
- typescript - 有什么方法可以过滤{}不放额外的地图吗?
- python - 欧米茄在连续过松弛率法中的意义是什么?
- python - 带有 fit_transfrom 或预测对象而不是拟合对象的 sklearn 管道