简体   繁体   中英

Django User cannot login

I made a simple register and login script, the register script works and sends the user information to a database but the login does not log the user in.

This is the login function in views.py:

from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from .forms import LoguserForm
# Create your views here.

def loginpage(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:
           login(request, user)
           return redirect('home')

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

This is the login.html file:

<body class="container">

    <div class="loginbox">
        <form id="login" class="input-group">
            {% load static %} <img src="{% static 'accounts/images/logo.png' %}" id="loginlogo">
            {% csrf_token %}
            <input type="text" class="inputfield" name="username" placeholder="Username">
            <input type="password" class="inputfield" name="password" placeholder="Password">
            <input type="submit" class="submitbtn" value="Login"></input>
            {% for message in messages %}
            <p>{{message}}</p>
            {% endfor %}
            <p1 class="registerp">New here? <a href="/register">Register</a></p1>
        </form>
    </div>

This is the homepage code:

def home(request):
    return HttpResponse('Home Page')

When I try to login instead of redirecting me to the home page the URL changes to:

http://127.0.0.1:8000/?csrfmiddlewaretoken=F63yG1ZNQTr4e6tRvjvj5TraSLeDDxAGCm1S89k4yuq21DyPgS4AlnfxA2KtnrA4&username=Tester&password=888tyuuyt

You need to add the operation method as POST and the url in your form tag as shown below.

<form action="your-login-endpoint/" id="login" class="input-group" method="post">
{% csrf_token %}
...
</form>

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