You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django后端验证:登录正常,错误凭证时如何显示错误信息?

Got it, let's fix that error message issue for your Django login page. The problem in your current code is that when authentication fails (wrong username/password) or the user doesn't exist, you're just redirecting to /dashboard/ without passing any error context to the login template. Here's how to adjust this step by step:

Step 1: Update the user_login view in views.py

We'll add an error message variable to hold our validation feedback, and pass it to the login template when authentication fails. We'll also clean up the request method handling for clarity:

from django.contrib.auth import authenticate, login as auth_login, logout

def user_login(request):
    # Only clear the login state when accessing the login page via GET
    if request.method == 'GET':
        logout(request)
    
    error_message = None
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        
        if user is not None:
            if user.is_active:
                auth_login(request, user)
                return render(request, 'admin_pannel.html', {'dept': dt, 'ds': ds})
        # Set error message if authentication fails
        error_message = "Invalid username or password. Please try again."
    
    # Pass error message (if any) to the login template
    return render(request, 'registration/login.html', {'dt': dt, 'error_message': error_message})

Key changes made:

  • Added an error_message variable that's only populated when authentication fails
  • Replaced if request.POST with the more explicit if request.method == 'POST'
  • Instead of redirecting on failure, we return the login template directly with the error context
  • Adjusted the logout call to only run on GET requests (prevents unexpected logouts during form submission)

Step 2: Add error display to your login template (registration/login.html)

Now we need to render the error message in the template when it exists. Add this snippet above your login form:

{% if error_message %}
    <div style="color: #dc3545; padding: 8px; margin-bottom: 1rem; border: 1px solid #f5c6cb; border-radius: 4px;">
        {{ error_message }}
    </div>
{% endif %}

<!-- Your existing login form -->
<form method="post">
    {% csrf_token %}
    <div>
        <label for="username">Username:</label>
        <input type="text" name="username" id="username" required>
    </div>
    <div>
        <label for="password">Password:</label>
        <input type="password" name="password" id="password" required>
    </div>
    <button type="submit">Login</button>
</form>

This will show a styled red alert box with your error message whenever the user enters invalid credentials. You can tweak the CSS styles to match your site's design.

Quick Notes:

  • Make sure you have all required imports at the top of views.py (we included the auth imports just in case)
  • Avoid redirecting after failed authentication—redirects trigger a new GET request, which makes it harder to pass context like error messages without using sessions
  • You can customize the error message text to be more specific if needed (e.g., "Username not found" or "Incorrect password") if you add extra checks for user existence

内容的提问来源于stack exchange,提问作者priya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:29:36