Django 包含在单个 urls.py 中

Django include within single urls.py

我想在我的 urls.py 中引用同一个 urls.py 文件中的另一个 url。

我的结构如下:

├── docs
├── requirements
├── scripts
└── sonata
    ├── person
    │   ├── migrations
    │   ├── templatetags
    │   └── urls.py
    ├── registration
    │   ├── migrations
    │   └── urls.py
    └── sonata
        ├── settings
        └── urls.py

而且我希望每个带有前缀 'pdf/' 的 url 都为 kwargs 添加一个值并再次调用 url 的其余部分。这是我的尝试:

urlpatterns = patterns('',
    url(r'^$',TemplateView.as_view(template_name='registration/login.html')),

    # This is my attempt for capturing the pdf prefix 
    # and calling this same file afterwards with the pdfOutput variable set to True
    url(r'^pdf/', include('sonata.urls'), kwargs={'pdfOutput':True}),

    url(r'^admin/', include(admin.site.urls)),
    url(r'^person/', include('person.urls')),
    url(r'^registration/', include('registration.urls')),
    url(r'^menu/', registration_views.menu, name='menu'),
    url(r'^customers/', person_views.customers, name='customers'),
    url(r'^employees/', person_views.employees, name='employees'),
    url(r'^alumns/', person_views.alumns, name='alumns'),
    url(r'^teaching/', person_views.docencia, name='teaching'),
    url(r'^i18n/', include('django.conf.urls.i18n')),
)

有什么办法吗?我看了文档。似乎很清楚如何传递值,但在证明我无法包含之后。 (我不想对重复所有 url 的 [array] 模式执行 include()。这会破坏 DRY 原则)。

提前致谢

问题是include立即导入包含的url配置,导致循环导入错误。不过,您可以这样做:

sonata_patterns = [
    url(r'^$',TemplateView.as_view(template_name='registration/login.html')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^person/', include('person.urls')),
    url(r'^registration/', include('registration.urls')),
    url(r'^menu/', registration_views.menu, name='menu'),
    url(r'^customers/', person_views.customers, name='customers'),
    url(r'^employees/', person_views.employees, name='employees'),
    url(r'^alumns/', person_views.alumns, name='alumns'),
    url(r'^teaching/', person_views.docencia, name='teaching'),
    url(r'^i18n/', include('django.conf.urls.i18n')),
]

urlpatterns = [
    url(r'^pdf/', include(sonata_patterns), kwargs={'pdfOutput':True})
] + sonata_patterns

另一种可能性是使用中间件来捕获pdf 前缀并在请求上设置一个属性。这样,如果所有视图都接受您的 pdfOutput 参数,您就不必担心。