我正在运行一个非常基本的django
登录应用程序(我认为)基于official docs并且......无论我在做什么,它仍然无法运行,而且我一直在查看StackOverflow上的每个问题而没有找到答案。我正在运行django.VERSION 1.5.0。
我在代码中添加或执行的任何操作都会导致CSRF verification failed
错误。
在我的 portal / views.py :
中@cache_page(60 * 15)
@csrf_protect
def index(request, id=None):
return render_to_response('undercovercoders/index.html', context_instance=RequestContext(request))
@cache_page(60 * 15)
def login_user(request):
if request.POST:
username = request.POST.get['username']
password = request.POST.get['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
state = "You're successfully logged in!"
else:
state = "Your account is not active, please contact the site admin."
else:
state = "Your username and/or password were incorrect."
return render_to_response('undercovercoders/index.html', {'state':state, 'username':username}, context_instance=RequestContext(request))
在我的 portal / templates / index.html :
中 <div id="login-box">
{% if form.errors %}
<p>Your username and password didn't match! Please try again!</p>
{% endif %}
{{ state }}
<form class="login-widgets" action="/login/" method="post">{% csrf_token %}
Username :
<input class="login-widgets-text" type="text" name="username" value="{{ username }}" />
{{ form.username }}<br />
Password :
<input type="password" name="password" value="{{ password }}" />
{{ form.password }}<br />
<input class="login-button" type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
在我的 urls.py / login /中定义了以下
(r'^login/$', 'portal.views.login'),
我的 settings.py 如下:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
请帮忙,我整个晚上一直在努力解决这个错误。
编辑:当我将更改添加到我的渲染时,我的控制台会将此返回给我:
/Library/Python/2.7/site-packages/django/template/defaulttags.py:59: UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.
warnings.warn("A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.")
[07/Aug/2013 21:44:25] "GET / HTTP/1.1" 200 2881
[07/Aug/2013 21:44:25] "GET /static/css/screen.css HTTP/1.1" 304 0
[07/Aug/2013 21:44:29] "POST /login/ HTTP/1.1" 403 2282
答案 0 :(得分:1)
在您的观点中
return render(request, 'template/index.html', {'state':state, 'username':username}, c)
你应该做
return render(request, 'template/index.html', {'state':state, 'username':username})
现在你传递c代替强制使用RequestContext的context_instance参数。