简体   繁体   中英

Django 403 Forbidden CSRF

recently I am seeing a weird error in my Django application. When I try to sign in, Chrome is stuck on "Processing request". After I click on the login button again it gives me the 403 Forbidden CSRF verification failed error. However, when I click on the Back button and press login again with the same user credentials it logs in successfully. I do not know why this is happening. I have two Django applications which 'home' and 'main', after correct credentials it should take the user to the view of 'home' applications.

My main/user_login.html

<form method="POST" action="{%url 'main:user_login' %}" class="form-signin">
                {% csrf_token %}
                <div class="form-label-group">
                  <input type="text" name="username" id="inputText" class="form-control" placeholder="Username" required autofocus>
                  <br/>
                </div>
                <div class="form-label-group">
                 <input type="password"  name="password" id="inputPassword" class="form-control" placeholder="Password" required>   
                </div>
                <div class="custom-control custom-checkbox mb-3">
                  <input type="checkbox" class="custom-control-input" id="customCheck1">
                  <label class="custom-control-label" for="customCheck1">Remember password</label>
                </div>
                <input type="submit" class="form-control" name="" value="Login">
                <hr class="my-4">
                <p>Don't have account? <a href="{% url 'main:signup' %}" id="signup">Sign up here</a></p>
                {% if message %}<p style="color: red;">{{ message }}</p>{% endif %}
                <a href="{% url 'password_reset' %}" id="signup">Forgot Password</a>
              </form>

my main/views.py:

def user_login(request):
    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:              
                login(request,user)
                messages.info(request, "Successfully signed in")
                return redirect(reverse('home:home')) 
            else:
                message = 'Sorry, the username or password you entered is not valid please try again.'
                return render(request, 'home/user_login.html', {'message':message})
        else:
            message = 'Sorry, the username or password you entered is not valid please try again.'
            return render(request, 'home/user_login.html', {'message':message})
    else:
        form=AuthenticationForm()
        return render(request, 'home/user_login.html', {"form":form})

my home/views.py:

@login_required

def home(request):
    context = {
        'posts': Post.objects.all()
    }
    return render(request, 'home/home.html', context)

I do not understand what is causing the issue which as I mentioned before after going back and clicking on login again the user can successfully login.

Thanks in advance!

Edit: I have realized what causes the error it is the else statement that throws the error message. I have changed my view right now it does not give me an error but I have to click on the login button twice else it would get stuck again. My view is now:

def user_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:
            return redirect('home:home')

        else:
            messages.error(request,'Sorry, the username or password you entered is not valid please try again.')
            return HttpResponseRedirect('/')
    else:
        form=AuthenticationForm()
        return render(request, 'main/user_login.html', {"form":form})

And my user_login.html is now:

      <form method="POST" action="{% url 'main:user_login' %}" class="form-signin">
        {% csrf_token %}
        <div class="form-label-group">
          <input type="text" name="username" id="inputText" class="form-control" placeholder="Username" required autofocus>
          <br/>
        </div>
        <div class="form-label-group">
         <input type="password"  name="password" id="inputPassword" class="form-control" placeholder="Password" required>   
        </div>
        <div class="custom-control custom-checkbox mb-3">
          <input type="checkbox" class="custom-control-input" id="customCheck1">
          <label class="custom-control-label" for="customCheck1">Remember password</label>
        </div>
        <input type="submit" class="form-control" name="" value="Login">
        <hr class="my-4">
        <p>Don't have account? <a href="{% url 'main:signup' %}" id="signup">Sign up here</a></p>
        {% for message in messages %}
          <p style="color: red;">{{ message }}</p>
        {% endfor %}
        <a href="{% url 'password_reset' %}" id="signup">Forgot Password</a>
      </form>

This is causing the issue:

 else:
     messages.error(request,'Sorry, the username or password you entered is not valid please try again.')
     return HttpResponseRedirect('/')

Try this one:

@login_required
def home(request):
     post = Post.objects.all()
     context = {'post':post}
     return render(request, 'home/home.html', context)

I think the problem might be in else block.

Just try this one:

def user_login(request):
  if request.method == 'POST':
    form = AuthenticationForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password')
        user = authenticate(username=username, password=password)
        if user is not None:              
            login(request,user)
            messages.info(request, "Successfully signed in")
            return redirect(reverse('home:home')) 

    else:
        message = 'Sorry, the username or password you entered is not valid please try again.'
        return render(request, 'home/user_login.html', {'message':message})
else:
    form=AuthenticationForm()
    return render(request, 'home/user_login.html', {"form":form})

Django's built-in tags need spaces

fix this in your form: action="{% url 'main:user_login' %}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM