需要建议。禁止 (403) CSRF 验证失败。请求被中止。 Django 错误

问题描述 投票:0回答:1

我正在使用 django 制作一个网站,当我登录并返回然后尝试再次登录时,我收到此错误消息。

禁止 (403)

CSRF验证失败。请求被中止。 失败原因给出: POST 中的 CSRF 令牌不正确。

当我第一次登录时,它工作正常,当我收到错误后,我返回并再次登录成功。 我只是想知道我的代码有什么问题。

这是views.py

`@csrf_protect
def login(request):

    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(request, username=username, password=password )
        
        if user is not None:
            auth_login(request, user)
            return redirect('homepage')
        else:
            messages.error(request, 'Username OR password is incorrect')
    

    context = {}
    return render(request, 'login.html', context)`

这是我的设置.py

`MIDDLEWARE = [
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
`

这是我的登录.html

`<form method="POST" action=" " >
                        
                        {% csrf_token %}
                        <div class="input-group mb-3">
                            <div class="input-group-append">
                                <span class="input-group-text"><i class="fas fa-user"></i></span>
                            </div>
                            <input type="text" name="username" class="form-control input_user" value="" placeholder="Username">
                        </div>
                        <div class="input-group mb-2">
                            <div class="input-group-append">
                                <span class="input-group-text"><i class="fas fa-key"></i></span>
                            </div>
                            <input type="password" name="password" class="form-control input_pass" value="" placeholder="Password">
                        </div>
                        <div class="form-group">
                            <div class="custom-control custom-checkbox">

                            </div>
                        </div>
                        
                    <div>
                {% for message in messages %}
                <p id="messages">{{message}}</p>
                {%endfor%}
                    </div>
                            <div class="d-flex justify-content-center mt-3 login_container">
                    <button type="submit" name="button" class="btn login_btn" >Login</button>
                   </div>
                    </form>

`
django csrf django-errors
1个回答
0
投票

@csrf_protect 是一个用于缓存实现的装饰器以及缓存装饰器(解释了所描述的行为)。

无论缓存有什么障碍,我建议您不要在登录表单中使用任何类型的缓存。只需从您的视图中删除@csrf_protect,您的代码就会运行。模板中的 {% csrf_token %} 将完成这项工作。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.