【问题标题】:Django: How to work with radio button in Django?Django:如何在 Django 中使用单选按钮?
【发布时间】:2020-07-31 10:39:31
【问题描述】:

我正在创建一个 MCQ 网络应用程序,用户将在其中选择一个答案,应用程序将当场返回答案是否正确。

models.py:

from django.db import models

#Tuple
SUBJECTS = (
    ('python','Python'),
    ('sql', 'SQL'),
    ('javascript','JavaScript'),
    ('java','Java'),
)

class Question(models.Model):
    subject = models.CharField(max_length=100, choices=SUBJECTS, default=None)
    question = models.TextField()
    opt1 = models.TextField()
    opt2 = models.TextField()
    opt3 = models.TextField(null=True)
    opt4 = models.TextField(null=True)
    correct_answer = models.TextField()


    def __str__(self):
        return self.question
    

views.py:

def practice(request):
    questions = Question.objects.all()
    return render(request,"practice.html",{'questions':questions})

练习.html:

{% for i in questions %}
    <div class="container border"><br />
    <h2>{{ i.question }} : </h2>
    <b>
    <hr></b>
    <div class="form-check p-2 ">
    <input class="form-check-input" type="radio" name="{{ i.id }}" id="{{ i.opt1 }}" value="{{ i.opt1 }}">
    <label class="form-check-label" for="{{ i.opt1 }}">
        {{ i.opt1 }}
    </label>
    </div>
    <hr>
    <div class="form-check  p-2 ">
    <input class="form-check-input" type="radio" name="{{ i.id }}" id="{{ i.opt2 }}" value="{{ i.opt2 }}">
    <label class="form-check-label" for="{{ i.opt2 }}">
        {{ i.opt2 }}
    </label>
    </div>
    <hr>
    <div class="form-check  p-2 ">
    <input class="form-check-input" type="radio" name="{{ i.id }}" id="{{ i.opt3 }}" value="{{ i.opt3 }}" >
    <label class="form-check-label" for="{{ i.opt3 }}">
        {{ i.opt3 }}
    </label>
    </div>
    <hr>
    <div class="form-check  p-2 ">
    <input class="form-check-input" type="radio" name="{{ i.id }}" id="{{ i.opt4 }}" value="{{ i.opt4 }}">
    <label class="form-check-label" for="{{ i.opt4 }}">
        {{ i.opt4 }}
    </label>
    </div>
    </div>
    <label hidden>{{ i.correct_answer }}</label>
    <br />
{% endfor %}

输出:

现在我想告诉用户他选择了正确答案还是错误答案,正确答案保存在{{ i.correct_answer }}中。

谁能帮我实现这个目标?

【问题讨论】:

    标签: python django django-forms django-templates


    【解决方案1】:

    您应该在您的 html 中添加一个提交按钮,该按钮会将答案发布到您的数据库。然后,在views.py中调用对象模型,实例化它,然后query它按照你想要的方式。

    【讨论】:

      猜你喜欢
      • 2020-08-17
      • 1970-01-01
      • 2013-05-08
      • 2012-05-01
      • 2010-11-28
      • 2020-11-12
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      相关资源
      最近更新 更多