Django - 'otherwise' 在 urls.py 中回退默认 URLConf

Django - 'otherwise' fallback default URLConf in urls.py

我有以下 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可以是任意数字

我想在其中放置一个 RegEx 来处理其他情况并将这些请求路由回 'home' 视图。但是我正在尝试的任何事情似乎都没有用。我尝试将这些作为我的 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

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

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

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')

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

在通常会导致 HTTP 404 的任何请求上显示主页并不是最佳做法,这会使人和机器人感到困惑。如果您仍然想这样做,最好使用 HTTP 301 redirect. For that purpose, Django has 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')

要解决您的静态文件问题,只需在您的 URL:

前 插入静态 URLs
# 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'))