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

时间:2018-12-06 07:36:54

标签: python django python-2.7 django-csrf

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

  

注意:我搜索了很多问题,尝试了各种答案,但在   大多数情况下,{% csrf_token %} HTML中缺少<form>   但就我而言,我也在使用它,这就是为什么不标记此   问题重复了,请!

这是我尝试过的:

来自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.')

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

谢谢!

1 个答案:

答案 0 :(得分:3)

您的问题在这里:

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

Docs about CSRF

  

在相应的视图函数中,确保RequestContext为   用于呈现响应,以便{%csrf_token%}可以正常工作   正确地。如果您使用render()函数,通用视图或   贡献应用程序,因为它们都已被使用   RequestContext。

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

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