python - Django CSRF验证失败

标签 python django forms csrf django-csrf

我是 Django 新手,我在 CSRF 验证方面遇到问题。到目前为止,我已经成功创建了 Django POST 表单,并且没有 CSRF 错误。但是当我尝试创建以下表单时,我收到 CSRF 验证失败:“CSRF token 丢失或不正确”。

{% for a in answers %}
    {% csrf_token %}
    <form class="" action="." method="post">
        <input type="submit" value="{{ a.answer }}" name={{a.answer_id}}></input>
    </form>
    <p>Number of votes: {{ a.votes }}</p>
{% empty %}
    <p>There are no answers for the poll</p>
{% endfor %}

以下是模型的样子:

class Question(models.Model):
    date_added = models.DateTimeField(auto_now_add=True)
    question = models.CharField(max_length=200)
    number_of_answers = models.IntegerField(default=0)

class Answer(models.Model):
    question = models.ForeignKey(Question)
    answer = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

该表单的 View 函数如下所示(到目前为止,我尚未添加任何代码来处理发布请求):

def poll(request, question_id):
    if request.method == "POST":
        pass
    poll = Question.objects.get(id=question_id)
    answers = poll.answer_set.order_by()
    context = {'poll' : poll, 'answers' : answers}
    return render(request, 'polls/poll.html', context)

基本上,每个问题都有多个答案。我想允许用户单击与特定答案关联的按钮。一旦用户单击按钮,我想增加数据库中对该答案的投票(我还没有添加执行此操作的代码,但这就是目标)。然后我希望页面重新加载新添加的投票。

Here is just an example of what this looks like visually

有人知道我做错了什么或者我错过了什么吗?

谢谢!

最佳答案

csrf token 位于表单内:

<form class="" action="." method="post">
 {% csrf_token %} <!--here goes the token-->
    <input type="submit" value="{{ a.answer }}" name={{a.answer_id}}></input>
</form>

关于python - Django CSRF验证失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47915232/

相关文章:

python - 使用 Zipfile 创建存档

python - 使用 Python 和 Keras 的 CNN

python - 使用 python 的 BaseHTTPRequestHandler 保持 HTTP 请求之间的状态

django 有条件过滤对象

django - django信号,如何使用“实例”

mysql - 如何根据自动增量 id 字段在 django 中降序排列查询集顺序

python - "RuntimeError: Working outside of application context "与 Python Flask 应用程序(使用调度程序发送 gmail)

javascript - 使用选择选项下拉更改图像,但对于多个事件?

javascript - 创建许多小的 html 表单

forms - 将 symfony2 表单标签制作成链接