将无效URL重新路由回djang的主页

2024-03-29 08:59:31 发布

您现在位置:Python中文网/ 问答频道 /正文

使用localhost:8000/admin/localhost:8000/效果很好。你知道吗

但我想忽略其他毫无意义的链接,比如本地主机:8000/adm让他们回到本地主机:8000/永久地。你知道吗

url works fine

from django.urls import path

from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView


from API import views
from API.views.Home import HomeView

urlpatterns = [
    path('grappelli/', include('grappelli.urls')), # grappelli URLS
    url(r'^admin/', admin.site.urls),
    url(r'^v1/', include('API.urls')),
    url(r'',HomeView.as_view(),name='HomeView'),
]

你知道吗?这可以简单地通过regex实现吗?你知道吗

更多示例。。。我想要达到的目标

localhost:8000/anything -> localhost:8000/
localhost:8000/anything/ -> localhost:8000/
localhost:8000/admin/anything -> localhost:8000/admin/
localhost:8000/admin/anything/ -> localhost:8000/admin/

简而言之,我想去掉多余的URL部分,这样它们甚至不会在浏览器中显示5xx重定向。你知道吗

在nginx中可以很容易地完成,但是我想知道在django中是否可以直接完成。你知道吗


Tags: pathdjangofromimportapilocalhosturlinclude
1条回答
网友
1楼 · 发布于 2024-03-29 08:59:31

使用regex的解决方案是:

url(r'^admin/.', admin.site.urls),
...
url(r'.',HomeView.as_view(),name='HomeView'),

但这会将原始url留在地址栏中。你知道吗

要摆脱它,请将重定向视图子类化:

url(r'^admin/$', admin.site.urls),
url(r'^admin/.', AdminRedirectView.as_view(), name='admin-redirect'),
...
url(r'^$',HomeView.as_view(),name='HomeView'),
url(r'^.$', HomeRedirectView.as_view(), name='home-redirect'),

# views.py
from django.views.generic.base import RedirectView

class HomeRedirectView(RedirectView):

    permanent = True
    query_string = False
    pattern_name = 'HomeView'

相关问题 更多 >