如何启动Django开发服务器时自动重定向至/login/页面?
To make your Django app automatically redirect from http://127.0.0.1:8000/ to the login page, you need to add a root URL pattern that handles this redirect. Here are two straightforward approaches to achieve this:
Approach 1: Use Django's Built-in RedirectView
This is the simplest method, leveraging Django's generic RedirectView class to point directly to your existing login URL by its name (best practice to avoid hardcoding paths).
Step 1: Update Your URL Configuration
Modify your project's urls.py file to include a root path that redirects to your login view:
from django.contrib import admin from django.urls import path from django.views.generic.base import RedirectView # Import RedirectView from .views import LoginIndexView urlpatterns = [ # Root path redirects to login page path('', RedirectView.as_view(pattern_name='loginindex', permanent=False), name='root'), path('login/', LoginIndexView.as_view(redirect_authenticated_user=True), name='loginindex'), # Add other URLs (like admin, list_view, etc.) here ]
Key Details:
pattern_name='loginindex': Uses the URL name you already defined for your login view. If you ever change the/login/path later, you won’t need to update this redirect.permanent=False: Sets a temporary 302 redirect (ideal here, as a permanent 301 would be cached by browsers and harder to adjust later).
Approach 2: Custom View for Authenticated User Optimization
If you want logged-in users to skip the login page and go directly to your list_view when accessing the root URL, create a simple custom view that checks the user’s authentication status:
Step 1: Add the Custom View
In your views.py file, add this function:
from django.shortcuts import redirect def root_redirect(request): if request.user.is_authenticated: # Redirect authenticated users straight to list_view return redirect('list_view') else: # Redirect unauthenticated users to login page return redirect('loginindex')
Step 2: Update URL Configuration
Modify your urls.py to use this custom view for the root path:
from django.contrib import admin from django.urls import path from .views import LoginIndexView, root_redirect # Import the custom view urlpatterns = [ path('', root_redirect, name='root'), path('login/', LoginIndexView.as_view(redirect_authenticated_user=True), name='loginindex'), # Ensure your list_view URL is defined here path('list/', YourListView.as_view(), name='list_view'), ]
Key Details:
- This view skips an extra redirect step for authenticated users, sending them directly to your main content instead of the login page.
- It maintains the desired behavior for unauthenticated users, redirecting them to the login page as requested.
Either approach will solve your original problem of auto-redirecting the root URL to the login page. The first is quick and minimal, while the second offers a smoother experience for logged-in users.
内容的提问来源于stack exchange,提问作者Ritish Ranjan Khan

