【问题标题】:Django CSRF verification failed even with {% csrf_token %} [duplicate]即使使用 {% csrf_token %} [重复],Django CSRF 验证也失败了
【发布时间】:2018-03-10 21:49:24
【问题描述】:

对以下 Django 视图的 POST 请求导致 (403) CSRF 验证失败。我已确认隐藏的 csrf 令牌已在页面源中呈现。我还能够在其他视图中发出 POST 请求而不会出错。我不确定如何进一步调试。

views.py:

def email(request):
    if request.method == 'POST':
        email = request.POST['email']
        fd = open('emaildb.csv','a')
        fd.write(email+',somefile\n')
        fd.close()
        return render(request, 'receipts/email.html', {'text':'Thanks, we''ll get back to you soon.'})
    else:
        return render(request, 'receipts/email.html',)

email.html:

<form action="email" method="post" enctype="text/plain">
    {% csrf_token %}
    E-mail:<br>
    <input type="text" name="email">
    <input type="submit" value="Send">
</form>

【问题讨论】:

  • 删除enctype="text/plain" 再试一次怎么样?也尽量不要使用action="email",而是使用action="{% url 'name_of_url' %}",或者如果你在同一个视图中发布,你可以完全省略action="email"。
  • 这并不意味着您拥有有效的令牌,即使您在页面源中看到它也是如此。它也可能过期。
  • nik_m 是正确的,只需删除 enctype="text/plain" 即可解决问题。

标签: python django csrf-protection django-csrf


【解决方案1】:

你不能这样调用方法

<form action="email" method="post" enctype="text/plain">
    {% csrf_token %}
    E-mail:<br>
    <input type="text" name="email">
    <input type="submit" value="Send">
</form>

在你的 urls.py 你必须写

url(r'^email/$', views.email, name='email')

并使用类似的形式调用此方法

<form action="{% url 'your_folder_name_where_located_your_urls.py:email'%}" method="post" enctype="text/plain">
    {% csrf_token %}
    E-mail:<br>
    <input type="text" name="email">
    <input type="submit" value="Send">
</form>

【讨论】:

    猜你喜欢
    • 2012-01-14
    • 1970-01-01
    • 2016-09-09
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 2012-09-08
    相关资源
    最近更新 更多