两个独立应用程序冲突中的 Django 相同 URL 模式

Django Identical URL Pattern in two Separate Apps Conflict

(Django v 1.10.4) 我正在尝试使用两个单独的应用程序,它们的 url 前缀是站点的根目录(我正在从另一个站点迁移到 django 并且需要维护现有的 url 结构)。有问题的两个 apps/models 是 "artistbio/Bio" 和 "pages/BasicPage"。目前我在主 url 配置中有 url 模式(最初它们在各自的 url.py 文件中,但我遇到的问题是相同的):

from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from artistbio.views import BioDetail
from pages.views import PageDetail


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^(?P<slug>[\w\-]+)/', PageDetail.as_view()),
    url(r'^(?P<slug>[-\w]+)/', BioDetail.as_view(), name='bio-detail'),

我读过的所有内容(以及我迄今为止的所有经验)都表明 Django 会在给出 "did not match any url patterns" 错误或“404”之前尝试将请求与每个 URL 模式匹配not found”错误,如果请求的对象确实不存在。但是现在当这两种模式如上所列时,当我通过 BioDetail 请求 Bio 对象时,它会尝试匹配 PageDetail 的 URL 模式并给我一个 404 错误(这是有道理的)但它似乎也意味着Django 永远不会移动到下一个肯定匹配的 URL 模式。如果我切换它们,并将 BioDetail 模式放在 PageDetail 模式之上,正如预期的那样,我就可以访问 Bio 对象但不能访问 Page 对象。

我已经阅读了我能找到的所有适用的 Whosebug 条目,阅读了所有官方文档并参考了 Django Unleashed,但似乎仍然缺少解决方案!

来自Django documentation

When a user requests a page from your Django-powered site, this is the algorithm the system follows to determine which Python code to execute:

  1. Django determines the root URLconf module to use. Ordinarily, this is the value of the ROOT_URLCONF setting, but if the incoming HttpRequest object has a urlconf attribute (set by middleware), its value will be used in place of the ROOT_URLCONF setting.
  2. Django loads that Python module and looks for the variable urlpatterns. This should be a Python list of django.conf.urls.url() instances.
  3. Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.
  4. Once one of the regexes matches, Django imports and calls the given view, which is a simple Python function (or a class-based view). [...]

关注第 3 点:一旦正则表达式验证当前 URL,Django 就会停止处理 urlpatterns 变量。它调用视图,如果该视图 return 出现 404,错误将 return 发送给客户端。

如果视图 returned 为 404,Django 将不会继续将 url 与以下模式匹配。

所以基本上,要解决您的问题,您必须编写一个与 URL 匹配的视图,分析 slug 并尝试获取相应的 PageBio(按此顺序)。但我建议您计划迁移到 Pages 和 Bio 有自己的视图来显示内容的系统。