【问题标题】:How to compare user input to corresponding model field django如何将用户输入与相应的模型字段 django 进行比较
【发布时间】:2020-04-24 20:46:25
【问题描述】:

我正在尝试为自己制作学习应用程序,我计划的一部分是制作一个测验模块。

我的问题是,我不知道如何将用户答案与模型中存储的正确答案进行比较。

现在,我唯一尝试过的(除了阅读文档和堆栈溢出)是在我的 HTML 中注入相关的模型问题,以便以后在 views.py 中使用,但从一开始我就觉得这不是方法它应该可以工作,所以我想我必须重新组织我的模型/表单或在 views.py 内部有一些方法可以查询数据库以获取我不知道的特定模型实例。

这是我的代码

型号:

class Question(models.Model):
        question = models.CharField(max_length=100, unique=True)
        answer = models.CharField(max_length=100, unique=False)

    def __str__(self):
        return self.question

表格:

class Answer(forms.Form):
    answer = forms.CharField()

观看次数:

def quiz(request):
    questions = Question.objects.order_by('question')
    form = Answer()
    context_dict = {'form':form,'questions':questions}
    if request.method == 'POST':
        form = Answer(request.POST)

        if form.is_valid():
        #Here I want to make the comparison
            pass
    return render(request,"quiz_app/quiz.html",context_dict)

HTML:

<table>
        {% for q in questions %}
            <tr>
                <td>{{ q.question }}</td>       
                <form method="POST">
                    <td>{{ form.answer }}</td>
                    {% csrf_token %}
                <td>
                    <input type="submit" value="submit">
                </td>
                </form>
            </tr>
        {% endfor %}
    </table>

【问题讨论】:

  • 您需要将您的Answer 表单链接到问题。您是否尝试过使用ModelForm 作为模型并使用Question 作为模型并使用附加字段作为用户答案?
  • 我已经尝试过这样做,但这根本不是一次成功的尝试。

标签: python html django django-models django-forms


【解决方案1】:

您可以将 question_id 与 post 请求一起传递,然后获取问题实例并比较结果。 HTML:

<form method="POST">
     <td>{{ form.answer }}</td>
      {% csrf_token %}
      <input type="hidden" name="q_id" value="{{ q.id }}" />
      <td>
          <input type="submit" value="submit">
      </td>
</form>

观看次数:

def quiz(request):
    questions = Question.objects.order_by('question')
    form = Answer()
    context_dict = {'form':form,'questions':questions}
    if request.method == 'POST':
        instance = Question.objects.get(id=request.POST['q_id'])
        form = Answer(request.POST, instance=instance)

        if form.is_valid():
        #Here I want to make the comparison
            if request.POST.get("answer").strip() == instance.answer:
                # used strip() to remove whitespace before and after the text.
                # other logic. 
    return render(request,"quiz_app/quiz.html",context_dict)

【讨论】:

  • 非常感谢!我不知道如何在视图中获取 HTML 输入,所以再次感谢您。现在,当我尝试实现它时,我收到一个错误“TypeError: __init__() got an unexpected keyword argument 'instance'”。我已经通过更改逻辑来修复它,但无论如何我很好奇,该怎么做?
  • 好吧,我的错。你的class Answer(forms.Form): 应该继承自forms.ModelForm。然后只有你可以通过实例。所以你的表格应该是class Answer(forms.ModelForm):
猜你喜欢
  • 2019-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多