虽然令牌在表单中,但CSRF验证失败

时间:2017-12-05 09:52:26

标签: python html django-templates django-csrf

您好社区我很难理解为什么会收到错误403.我尝试在Stackoverflow上寻找答案,但这里的问题是由于缺少{% csrf_token %}而导致的。下面是我的html文件:

<form action="{% url 'authentication:user_login' %}" style="display: block;" method="POST">
                                {% csrf_token %}
                                <label for="username">Username:</label>
                                <input id="username" type="text" name="username" placeholder="Enter Username" tabindex="1" class="form-control">

                                <label for="password">Password:</label>
                                <input id="password" type="password" name="password" tabindex="=2" class="form-control" placeholder="Password">

                                <button type="submit" class="btn btn-success">Login</button> or <a href="{% url 'authentication:register' %}">register</a> here
                            </form>

以下是与网址对应的视图:

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

        user = authenticate(username=username, password=password)

        if user:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect(reverse('homepage'))  # main page if login is successful

            else:
                return HttpResponse("ACCOUNT NOT ACTIVE")

        else:
            print('Someone tried to log in and failed')
            print('Username: {}, password, {}'.format(username, password))
            return HttpResponse('Invalid login details supplied')

    else:
        return render(request, 'authentication/login.html', {})

以下是urls.py中的网址:

url(r'^user_login/$', views.user_login, name='user_login'),

我在某处读到csrf_token有一个部分可以在render()函数中播放,但我不完全确定它与任何东西有什么关系。

修改

这是我的settings.py

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

更新

我设法解决了这个问题,虽然我不确定它是否是解决问题的正确方法。 负责呈现该html的视图要求其返回类型为render(request, authentication/login.html)HttpResponse(template.render())

相比

0 个答案:

没有答案