Django登录功能错误消息无法正常显示的技术求助
Hey there! I see you're having trouble getting error messages to display when a user enters invalid credentials in your Django login form. Let's break down the issues and fix them step by step.
1. Core Problem: Your Template Isn't Rendering Django's Messages
Looking at your code, you're using Django's messages.error() in your view to add error alerts, but your template is checking for form.errors instead. Since you're handling authentication manually (not using a Django auth form) and never passing a form instance to the template, those form.errors will never populate or show up.
Fix: Add Messages Rendering to Your Template
Replace the form.errors block in your login_register.html with code that renders Django's messages framework:
<div class="login-form"> <form action="" method="POST"> {% csrf_token %} <!-- Render Django error messages here --> {% if messages %} {% for message in messages %} <p class="text-danger">{{ message }}</p> {% endfor %} {% endif %} <h2 class="text-center">Sign in</h2> <!-- Rest of your form content stays the same --> </form> </div>
This will now display any error messages you add via messages.error() in your view.
2. View Logic Improvements
Your login view has a couple of small issues that can cause unexpected behavior:
- When a username doesn't exist, you add an error message but still run
authenticate(), which triggers a second duplicate error. - You're not explicitly passing context to the template in all code paths.
Updated Login View Code
Here's the revised loginUser function with fixes:
def loginUser(request): page = 'login' if request.user.is_authenticated: return redirect('starting-page') if request.method == 'POST': username = request.POST['username'].lower() password = request.POST['password'] try: # Check if user exists in database user = User.objects.get(username=username) except User.DoesNotExist: messages.error(request, 'Username does not exist') # Return immediately to avoid duplicate error messages return render(request, 'users/login_register.html', {'page': page}) # Authenticate the user with provided credentials user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Use .get() to safely handle missing 'next' parameter return redirect(request.GET.get('next', 'starting-page')) else: messages.error(request, 'Username OR password is incorrect') return render(request, 'users/login_register.html', {'page': page}) # Handle GET requests (display empty login form) return render(request, 'users/login_register.html', {'page': page})
3. Minor Cleanup: Duplicate URL Pattern
Your urls.py has two paths pointing to the same login view:
path('', views.loginUser, name="login"), path('login/', views.loginUser, name="login"),
This isn't a critical bug, but it's redundant. Pick one (I recommend keeping path('login/', views.loginUser, name="login"),) and remove the other to avoid confusion.
Final Quick Checks
Make sure your project's settings.py has these required components (they're enabled by default in most Django projects):
'django.contrib.messages'included inINSTALLED_APPSdjango.contrib.sessions.middleware.SessionMiddlewareanddjango.contrib.messages.middleware.MessageMiddlewarelisted inMIDDLEWARE
After making these changes, your error messages should display correctly when users enter invalid usernames or passwords!
内容的提问来源于stack exchange,提问作者Đỗ Văn Hỏa 4C-18

