Django投掷" CSRF令牌丢失或不正确"错误(因为csrfmiddlewaretoken为空值)

时间:2014-12-31 14:16:51

标签: python django cookies csrf

我最近遇到了一个非常奇怪的问题。我的模板中有一个表单如下:

<form class="form" id="loginForm" role="form" action="/user/login/" 
  method="POST">
{% csrf_token %}
<div class="form-group">
    <input type="email" class="form-control" id="email" name="email"
     placeholder="Enter email" value="">
</div>
<div class="form-group">
    <input type="password" class="form-control" id="password"
     name="password" placeholder="Password" value="">
</div>
<div class="cl-effect-7">
    <button type="submit" class="btn btn-primary">SIGN IN</button>
</div>
</form>

我得到了 CSRF token missing or incorrect 。深入挖掘我发现虽然 csrftoken cookie在浏览器中正确设置,但POST请求的空值为 csrfmiddlewaretoken ,因此它会抛出错误并带有上述原因。
这也是我的观点(虽然我怀疑它是否有任何问题)

def user_login(request):
    context = RequestContext(request)
    if request.method == 'POST':
        email = request.POST['email']
        password = request.POST['password']
        user = authenticate(username=email, password=password)
        if user:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/user/')
            else:
                return HttpResponse("Your account is disabled.")
        else:
            return HttpResponse("Invalid login details supplied.")
    else:
        return render_to_response('user/login.html', {},context_instance = context)

以下是重定向到login.html的其他视图:

def index(request):
    context_dict = {}
    template = "user/login.html" #default template to render
    user = None
    user_profile = None

    user = request.user.id
    if user != None:
        user_profile,created = UserProfile.objects.get_or_create(user=user)

    #Check whether the user is new,if yes then he needs to select btw Mentor-Mentee
    if user_profile and user_profile.is_new:
        context_dict['selected'] = None
        template = "user/select.html" #User has to select either Mentor/Mentee,so redirect to select.html


    return render_to_response(template,context_dict,context_instance = RequestContext(request))

现在我使用小JavaScript来解决这个问题,通过手动设置cookie中的csrfmiddlewaretoken的值,但这是Django的一个奇怪的行为。
PS:我正在使用 Django 1.7 并在所有浏览器上进行测试。

1 个答案:

答案 0 :(得分:-3)

尝试将此添加到您的表单:

<div style="display:none">
    <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
</div>

来源:https://docs.djangoproject.com/en/dev/ref/csrf/#other-template-engines