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

Django中如何将/api/v1/poll/重定向至/poll/?

How to Redirect /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=True for a 301 permanent redirect (ideal if this is a permanent URL change). Use permanent=False for 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/:

  1. Update your root urls.py to include the API v1 URLs:
urlpatterns = [
    path('poll/', include('myproject.poll.urls')),
    path('api/v1/', include('myproject.api_v1.urls')),
]
  1. Create a new file myproject/api_v1/urls.py and 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:07:10