即使在表单 html 中添加 csrf_token 标记后,Django CSRF 验证仍失败

Django CSRF verification failed even after adding csrf_token tag inside the form html

我正在使用 Python(2.7) 和 Django(1.10) 开发一个项目,我需要在其中提交登录表单,但 returns 提交时出错。

Note: I have searched a lot of questions tried various answers but in most cases the {% csrf_token %} is missing from the <form> HTML but in my case, I'm using this also, that's why don't mark this question duplicated, please!

这是我尝试过的方法:

来自 form.html:

<form class="fields-signup" action="{% url 'mainlogin' %}" method="post">


{% csrf_token %}
            <h1 class="text-center">Sign In</h1>
            <div class="form-group">
                <input class="user-name form-control" type="text"  name="username" placeholder="User name">
            </div>
            <div class="form-group">
                <input class="password form-control" type="password"   placeholder="Password" name="password">
            </div>
            <input type="submit" class="btn siteBtn" value="Sign In">
            <!-- <a href="#" class="btn siteBtn" >Sign Up</a>
            <p class="text-center">Don’t Have an account? <a href="#">Signup</a></p> -->


            <!--popup-forget-password-->
            <div class="col-sm-12">
             <button type='button' class="forget-password-btn" data-toggle="modal" data-target="#popUpWindow">Forgot Password</button> 
              <!--forget-password-end-->
                <div class="col-sm-12 register">
                 <a class="register-driver-btn" data-toggle="modal" data-target="#popUpWindow_register">Register Driver?</a> 
                </div>
            </div>
</form>

来自 urls.py:

url(r'^$', views.home, name="home"),

来自 views.py:

    if request.method == "GET":
    try:
        temp = get_template('login.html')
        result = temp.render(Context({'context': RequestContext(request)}))
        return HttpResponse(result)

来自 views.py 的更多内容:

    if request.method == "POST":
    username = request.POST['username']
    # email = request.POST['email']
    password = request.POST['password']
    try:
        #obj = User_table.objects.get(user_name=username, emailid=email)
        obj = User_table.objects.get(user_name=username)
        if obj:
            print('got user obj')
        verify_password = ''
        try:
            verify_password = handler.verify(password, obj.password)
        except Exception as e:
            print(e)
        if verify_password is True:
            request.session['user_id'] = obj.id
            request.session['user_type'] = obj.user_type
            user_name = obj.first_name + ' ' + obj.last_name
            request.session['user_name'] = user_name
            if not obj.approval_status:
                return HttpResponse('Your account is not confirmed by administration.')
            obj.is_active = True
            obj.login_try = 0
            obj.save()
            return redirect(home)
        else:
            try:
                # obj = User_table.objects.get(user_name=username, emailid=email)
                obj = User_table.objects.get(user_name=username)
                if obj:
                    s = obj.login_try
                    s = s + 1
                    obj.login_try = int(s)

                    if int(obj.login_try) >= 3:
                        obj.login_try = 3
                    obj.save()
                    if int(obj.login_try) == 3:
                        id = obj.id
                        key = get_random_string(length=10)
                        reset_link = 'It seems you forgot password or someone is trying to login you account. This is your password reset link please do not share this with other ' + settings.EMAIL_URL + 'reset_password/' + str(
                            id) + ' key is : ' + str(key)
                        send_mail('Reset link', reset_link, settings.EMAIL_HOST_USER, [obj.emailid, ])
                        obj.password = str(key)
                        obj.save()
                        return HttpResponse(
                            'It seems you forgot password or someone is trying to login you account.  Password Reset link has been sent to your email id')
            except Exception as e:
                print(e)
                pass
            return redirect(mainlogin)
    except Exception as e:
        print('error is  : ', e)
        return HttpResponse('An error has occurred.')

此外,我在 settings.py 中包含了 csrf 中间件。 这里有什么问题吗?

提前致谢!

你的问题在这里:

if request.method == "GET":
    try:
        temp = get_template('login.html')
        result = temp.render(Context({'context': RequestContext(request)}))
        return HttpResponse(result)

Docs about CSRF

In the corresponding view functions, ensure that RequestContext is used to render the response so that {% csrf_token %} will work properly. If you’re using the render() function, generic views, or contrib apps, you are covered already since these all use RequestContext.

我不确定为什么会这样,可能上下文处理器配置有问题,其中之一将 csrf_token 添加到上下文字典。 有关更多调试信息,请参阅 RequestContext 部分。但是使用内置 render() 函数将解决您的问题,因为它会为您处理上下文。

from django.shortcuts import render
if request.method == "GET":
    ...
    return render(request, 'login.html')