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

2024-10-03 04:30:16 发布

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

(Django v 1.10.4) 我尝试使用两个独立的应用程序,它们的url前缀是站点的根(我正在从另一个站点迁移到django,需要维护现有的url结构)。有问题的两个应用程序/模型是“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将尝试根据每个URL模式匹配请求,然后给出“不匹配任何URL模式”错误或“404未找到”错误(如果请求的对象确实不存在)。但是现在,当两个模式都在一起时,当我通过BioDetail请求一个Bio对象时,它会尝试与PageDetail的URL模式相匹配,并给出404错误(这是有意义的),但这似乎也意味着Django永远不会转到下一个URL模式,它肯定是匹配的。如果我切换它们,并将BioDetail模式放在PageDetail模式之上,那么我就可以访问Bio对象而不是页面对象。在

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


Tags: 对象djangofromimport应用程序urladmin站点
1条回答
网友
1楼 · 发布于 2024-10-03 04:30:16

来自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点:一旦regexp验证了当前URL,Django就停止处理urlpatterns变量。它调用视图,如果该视图返回404,则将错误返回给客户端。在

如果视图返回404,Django将不会继续使用以下模式匹配url。在

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

相关问题 更多 >