Django包含在单个urls.py中

时间:2015-04-05 11:38:41

标签: django django-views django-urls

我想在我的urls.py中创建一个include,引用同一个urls.py文件中的其他网址。

我的结构如下:

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

我希望每个即将到来的网址都带有前缀' pdf /'为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')),
)

有没有办法做到这一点?我查看了文档。似乎很清楚如何传递值,但在证明我无法做出包含之后。 (我不想让include()重复所有网址的[数组]模式。这会打破DRY原则。)

提前致谢

1 个答案:

答案 0 :(得分:2)

问题是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参数,您就不必担心了。