您好,我是一个新手,试图使用 django 注册一些用户,我一直在阅读 Django Book 并且正在阅读关于注册的章节,http://www.djangobook.com/en/2.0/chapter14/当我这样做时指示我明白了
禁止 (403)
CSRF 验证失败。请求中止。帮助
失败原因:
CSRF token missing or incorrect.
通常,当存在真正的跨站点请求伪造时,或者未正确使用 Django 的 CSRF 机制时,可能会发生这种情况。对于 POST 表单,您需要确保:
Your browser is accepting cookies.
The view function uses RequestContext for the template, instead of Context.
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
您看到此页面的帮助部分是因为您的 Django 设置文件中有 DEBUG = True 。将其更改为 False,将仅显示初始错误消息。
您可以使用 CSRF_FAILURE_VIEW 设置自定义此页面。
我将 {% csrf_token %} 模板标签放在post 标签内,它仍然给我这个错误。谢谢
# views.py
#
# Copyright 2012 Talisman <KlanestroTalisman@gmail.com>
from django.shortcuts import render_to_response
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
def home (request):
return render_to_response('FirstTemplate.html',)
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/books/")
else:
form = UserCreationForm()
return render_to_response("register.html", {
'form': form,
})
形式
{% extends "base.html" %}
{% block title %}Create an account{% endblock %}
{% block content %}
<h1>Create an account</h1>
<form action="" method="post"{% csrf_token %}>
{{ form.as_p }}
<input type="submit" value="Create the account">
</form>
{% endblock %}