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:
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>
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')
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')), ]
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>
- Use
is_superuserinstead ofis_staffif you only want to redirect super admins (users with all permissions) to the admin dashboard. - The
@login_requireddecorator 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

