尝试在django中实现csrf时出现此错误。 禁止的(403) CSRF验证失败。请求中止。 救命 失败的原因: CSRF令牌丢失或不正确。 (和bla bla bla) 我的Views.py显示如下:
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
from django.contrib.auth.forms import UserCreationForm
def login(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return HttpResponseRedirect('/accounts/loggedin')
else:
return HttpResponseRedirect('/accounts/invalid')
def loggedin(request):
return render_to_response('loggedin.html',{'full_name':request.user.username})
def invalid_login(request):
return render_to_response('invalid_login.html')
def logout(request):
auth.logout(request)
return render_to_response('logout.html')
def register_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
args ={}
args.update(csrf(request))
args['form'] = UserCreationForm()
return render_to_response('register.html')
def register_success(request):
return render_to_response('register_success.html')
我的register.html反映如下:
{% extends 'base.html' %}
{% block content %}
<h2>Register</h2>
<form action="/accounts/register/" method="post">{% csrf_token %}
{{ form }}
<input type="submit" value="Register"/>
</form>
{% endblock %}
在urls.py中:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^articles/', include('article.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/login/$', 'django_test.views.login'),
url(r'^accounts/auth/$', 'django_test.views.auth_view'),
url(r'^accounts/logout/$', 'django_test.views.logout'),
url(r'^accounts/loggedin/$', 'django_test.views.loggedin'),
url(r'^accounts/invalid/$', 'django_test.views.invalid_login'),
url(r'^accounts/register/$', 'django_test.views.register_user'),
url(r'^accounts/register_success/$', 'django_test.views.register_success'),
)
请指教。我在浏览器中启用了cookie。
答案 0 :(得分:1)
在register.html中,您需要在<form> </form>
中添加csrf令牌,如下所示:{% csrf_token %}
,希望它能解决问题。
答案 1 :(得分:0)
这可能不是最佳做法,但您可以添加:
@csrf_exempt
位于view.py文件中的函数上方。
请参阅django-rest-framework教程中的示例: Writing regular Django views