Django中如何将/api/v1/poll/重定向至/poll/?
/api/v1/poll/ to /poll/ in Your Django Poll App Hey there, let's get that redirect set up for your poll application. I've got two simple, reliable methods for you to choose from, depending on your project structure:
Method 1: Add the Redirect Directly in Your Root URLconf
This is the quickest fix—no changes needed to your existing Poll app URLs. Just open your project's root urls.py and add a new path using Django's built-in RedirectView:
from django.urls import path, include from django.views.generic.base import RedirectView urlpatterns = [ path('poll/', include('myproject.poll.urls')), # Redirect /api/v1/poll/ to /poll/ path('api/v1/poll/', RedirectView.as_view(url='/poll/', permanent=True)), # Optional: Handle requests without the trailing slash too path('api/v1/poll', RedirectView.as_view(url='/poll/', permanent=True)), ]
- Set
permanent=Truefor a 301 permanent redirect (ideal if this is a permanent URL change). Usepermanent=Falsefor a temporary 302 redirect if you might switch things back later. - The second path is optional but helpful for users who might type the URL without the trailing slash.
Method 2: Centralize Redirects in an API Version URLconf
If you plan to have more API version-related redirects or want to keep your root URLconf clean, create a separate URL file for /api/v1/:
- Update your root
urls.pyto include the API v1 URLs:
urlpatterns = [ path('poll/', include('myproject.poll.urls')), path('api/v1/', include('myproject.api_v1.urls')), ]
- Create a new file
myproject/api_v1/urls.pyand add the redirect rule there:
from django.urls import path from django.views.generic.base import RedirectView urlpatterns = [ path('poll/', RedirectView.as_view(url='/poll/', permanent=True)), path('poll', RedirectView.as_view(url='/poll/', permanent=True)), ]
This keeps all your API version-related routing organized in one place, which is great for larger projects.
Quick Note
Since you're using DRF's DefaultRouter, it automatically uses trailing slashes (default trailing_slash=True), so redirecting to /poll/ (with the slash) matches your existing endpoints perfectly—no 404s to worry about here.
内容的提问来源于stack exchange,提问作者fuzes

