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

Django中同一登录模板下区分管理员与普通用户登录的方法

Got it, let's walk through how to set up a single login template in Django that redirects admins and regular users to different pages after successful login. This is a common use case, and the implementation is straightforward once you break it down:

Step 1: Create a Single Reusable Login Template

First, build a single login form that both admins and regular users will use. No need for separate templates here—we'll handle the routing logic on the backend.

<!-- templates/accounts/login.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
    <style>
        .error { color: red; margin-bottom: 10px; }
        .form-group { margin: 10px 0; }
    </style>
</head>
<body>
    <h2>Login to Your Account</h2>
    {% if error %}
        <p class="error">{{ error }}</p>
    {% endif %}
    <form method="post">
        {% csrf_token %}
        <div class="form-group">
            <label for="username">Username:</label>
            <input type="text" id="username" name="username" required>
        </div>
        <div class="form-group">
            <label for="password">Password:</label>
            <input type="password" id="password" name="password" required>
        </div>
        <button type="submit">Sign In</button>
    </form>
</body>
</html>
Step 2: Build the Login View with User Type Routing

Next, create a view that handles authentication, then redirects users based on their admin status. We'll use Django's built-in authenticate and login functions, plus check the user's is_staff or is_superuser field (use is_superuser if you want to restrict to only super admins, is_staff for any user with admin panel access).

# accounts/views.py
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required

def user_login(request):
    if request.method == 'POST':
        # Get credentials from form submission
        username = request.POST.get('username')
        password = request.POST.get('password')
        
        # Authenticate the user
        user = authenticate(request, username=username, password=password)
        
        if user is not None:
            # Log the user in
            login(request, user)
            
            # Redirect based on user type
            if user.is_staff:
                return redirect('admin_dashboard')
            else:
                return redirect('user_dashboard')
        else:
            # Invalid credentials, return to login with error
            return render(request, 'accounts/login.html', {'error': 'Invalid username or password'})
    # GET request: show login form
    return render(request, 'accounts/login.html')

# Admin dashboard view (restricted to staff users)
@login_required
def admin_dashboard(request):
    # Extra security: block non-admins from accessing this URL directly
    if not request.user.is_staff:
        return redirect('user_dashboard')
    return render(request, 'accounts/admin_dashboard.html')

# Regular user dashboard view
@login_required
def user_dashboard(request):
    # Optional: redirect admins who land here by mistake
    if request.user.is_staff:
        return redirect('admin_dashboard')
    return render(request, 'accounts/user_dashboard.html')

# Logout view
def user_logout(request):
    logout(request)
    return redirect('login')
Step 3: Configure URL Routes

Map your views to URLs so Django knows where to send requests.

# accounts/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('login/', views.user_login, name='login'),
    path('admin-dashboard/', views.admin_dashboard, name='admin_dashboard'),
    path('user-dashboard/', views.user_dashboard, name='user_dashboard'),
    path('logout/', views.user_logout, name='logout'),
]

Don't forget to include these URLs in your project's main urls.py:

# your_project/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('accounts.urls')),
]
Step 4: Create Dashboard Templates

Finally, build the two distinct dashboard pages for admins and regular users:

<!-- templates/accounts/admin_dashboard.html -->
<h2>Admin Dashboard</h2>
<p>Welcome back, {{ user.username }}! You have full administrative access.</p>
<p><a href="{% url 'logout' %}">Sign Out</a></p>
<!-- templates/accounts/user_dashboard.html -->
<h2>Your Dashboard</h2>
<p>Welcome back, {{ user.username }}! This is your personal account page.</p>
<p><a href="{% url 'logout' %}">Sign Out</a></p>
Quick Notes
  • Use is_superuser instead of is_staff if you only want to redirect super admins (users with all permissions) to the admin dashboard.
  • The @login_required decorator ensures only logged-in users can access the dashboards.
  • We added extra checks in the dashboard views to prevent users from manually typing the URL to access a restricted page.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:14:22