CSRF验证失败。请求中止。给出失败原因:CSRF令牌丢失或不正确。使用Django

时间:2020-06-17 15:45:18

标签: python html django django-csrf csrf-token

我一直收到消息,并已尝试/确保:

  1. 我的浏览器正在接受Cookie

  2. 视图功能将请求传递给Views.py文件中模板的render方法:

Views.py文件##

**from django.shortcuts import render, redirect**
from django.contrib.auth.models import User
from django.contrib import auth

def signup(request):
    if request.method == 'POST':
        # User has info and wants an account now!
        if request.POST['password1'] == request.POST['password2']:
            try:
                user = User.objects.get(username=request.POST['username'])
                return render(request, 'accounts/signup.html', {'error':'Username has already been taken'})
            except User.DoesNotExist:
                user = User.objects.create_user(request.POST['username'], password=request.POST['password1'])
                auth.login(request,user)
                return redirect('home')
        else:
            return render(request, 'accounts/signup.html', {'error': 'Passwords must match'})
    else:
        # User wants to enter info
        return render(request, 'accounts/signup.html')

def login(request):
    if request.method == 'POST':
        user = auth.authenticate(username=request.POST['username'],password=request.POST['password'])
        if user is not None:
            auth.login(request, user)
            return redirect('home')
        else:
            return render(request, 'accounts/login.html', {'error': 'Usename or password is invalid'})
    else:
        return render(request, 'accounts/login.html')

def logout(request):
    if request.method == 'POST':
        auth.logout(request)
        return redirect('home')
    # Need to route to home page
    return render(request, 'accounts/signup.html')
  1. 我在模板中为每个以内部URL为目标的POST表单中添加了{%csrf_token%}:

  <form class="form-signin" method="POST" action="{% url 'signup' %}">
{% csrf_token %}
<input class="form-control" placeholder="Username" required autofocus type="text" name="username" />
<input class="form-control" placeholder="Password" required autofocus type="password" name="password1" />
<input class="form-control" placeholder="Confirm Password" required autofocus type="password" name="password2" />
<br/>
<br/>
<button class="btn waves-effect waves-light" type="submit">Sign UP!</button>
<br/>
  </form>

  1. 我已确保CsrfViewMiddleware位于我的设置文件中:

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

请帮助!谢谢。

0 个答案:

没有答案