python - Django User Authentication Not Working, Login Verification Fails - Stack Overflow

I'm developing a web application using the Django framework. Currently, I'm facing an issue w

I'm developing a web application using the Django framework. Currently, I'm facing an issue with the user authentication part. I've followed the steps in the official documentation, but the user login verification always fails. I've configured the following in my settings.py:

INSTALLED_APPS = [
    # Other apps
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
]

LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'

My user model is the default User model. In the login view, I use the following code for verification:

from django.contrib.auth import authenticate, login
from django.shortcuts import render, redirect

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:
            login(request, user)
            return redirect('home')
        else:
            return render(request, 'login.html', {'error': 'Incorrect username or password'})
    return render(request, 'login.html')

My login.html form is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <form method="post">
        {% csrf_token %}
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" required><br>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" required><br>
        <input type="submit" value="Login">
        {% if error %}
            <p>{{ error }}</p>
        {% endif %}
    </form>
</body>
</html>

I've ensured that the corresponding username and password exist in the database, but every time I try to log in, it prompts "Incorrect username or password". I've checked the password storage format in the database, and it seems to be a normal hash value. I've tried restarting the server, clearing the browser cache, and even recreating test users, but the problem still persists. Does anyone know what might be causing this? How can I solve this problem? Also, if there's any additional information you need from me, please let me know.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744715535a4589597.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信