【问题标题】:Django - 'otherwise' fallback default URLConf in urls.pyDjango - urls.py 中的“否则”后备默认 URLConf
【发布时间】:2016-01-01 16:48:14
【问题描述】:

我有以下 urls.py:

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

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', 'news_readr.views.home', name='home'),
    url(r'^details/(?P<article_id>[0-9]+)$', 'news_readr.views.details', name='details'),
    url(r'^details/$', 'news_readr.views.details', name='details'),
    url(r'^/$', 'news_readr.views.home', name='home'),
]


if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

我的应用中有两个有效的 URL:

  1. 本地主机:8000/
  2. localhost:8000/details/123 #其中123可以是任意数字

我想在其中放置一个正则表达式来处理其他情况并将这些请求路由回“主”视图。但我尝试的任何方法似乎都不起作用。我尝试将这些作为我的 urlpattern 的最后一行:

url(r'^/$', 'news_readr.views.home', name='home'), #this does nothing
url(r'', 'news_readr.views.home', name='home'), #this redirects fine to my homepage, but breaks all of my media and static paths, and causes my images to not load

我可以使用更好的方法或正确的正则表达式来解决这种情况吗?

【问题讨论】:

    标签: python regex django django-urls url-pattern


    【解决方案1】:

    在通常会导致 HTTP 404 的任何请求上显示主页并不是最佳做法,这会使人和机器人感到困惑。如果您仍然想这样做,最好使用HTTP 301 重定向。为此,Django 有RedirectView:

    from django.core.urlresolvers import reverse
    from django.views.generic import RedirectView
    
    class RedirectToHome(RedirectView):
    
        def get_redirect_url(self, *args, **kwargs):
            return reverse('home')
    

    要解决您的静态文件问题,只需在您的所有网址之前插入静态网址

    # You don't have to check DEBUG because static() does nothing if DEBUG is False.
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    
    urlpatterns.append(url(r'^.*$', views.RedirectToHome.as_view(), name='redirect_to_home'))
    

    【讨论】:

    • 谢谢,成功了!我只是在尝试 POC,所以我还没有看到机器人等。非常感谢您的建议!
    【解决方案2】:

    在静态和媒体网址之后添加重定向正则表达式:

    if settings.DEBUG:
        urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
        urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    
    urlpatterns += url(r'', 'news_readr.views.home', name='home')
    

    在所有其他 url 之后添加这个正则表达式将使它成为最后的选择。

    【讨论】:

    • (在 django 1.10.5 上)此方法会导致错误 TypeError: 'RegexURLPattern' object is not iterable。解决方案是使用urlpatterns.append(url(...)) 而不是urlpatterns += url(...)
    • @danyamachine 是的,在 1.10 中,您需要将 urlpatterns 指定为列表。因此出现了问题。
    猜你喜欢
    • 2011-03-06
    • 2012-07-22
    • 2014-06-14
    • 2013-07-12
    • 2011-04-15
    • 2012-07-11
    • 2022-11-13
    • 1970-01-01
    • 2013-06-01
    相关资源
    最近更新 更多