【发布时间】: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