即使使用必要的令牌,也会发生CSRF错误

时间:2015-10-11 13:20:39

标签: django csrf

我正在尝试创建一个简单的logIn页面。我理解CSRF的概念,但即使使用令牌和导入以及必要的中间件,我仍然会收到403(禁止)错误。

请帮忙!我做错了什么?

views.py:

from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, login
from django.core.context_processors import csrf

def login_user(request):
   state = "Please log in below..."
   username = password = ''
   c = {}
   c.update(csrf(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('auth.html',{'state':state, 'username': username}, c)

auth.html:

<html>
<head>
<title>Log in</title>
 <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
 <style>
 body{
     font-family:Arial,Helvetica,sans-serif;
     font-size: 12px;
 }
 </style>
 </head>

<body>
    {{ state }}
    <form action="/login/" method="post"> {% csrf_token %}
        {% if next %}
        <input type="hidden" name="next" value="{{ next }}" />
        {% endif %}
        username: 
        <input type="text" name="username" value="{{ username}}" /><br />
        password:
        <input type="password" name="password" value="" /><br />

        <input type="submit" value="Log In" />
    </form>
</body>
</html>

注意:代码来自http://solutoire.com/2009/02/26/django-series-1-a-custom-login-page/

1 个答案:

答案 0 :(得分:0)

你在login_user函数中有很多不必要的代码。您无需手动添加csrf_token;但是如果你这样做,你可以在模板上下文字典本身中进行,而不是在单独的参数中进行。

您应该删除两行c = {}c.update(csrf(request)),并在函数末尾执行此操作:

return render(request, 'auth.html',{'state':state, 'username': username})