How do you use Django URL namespaces?

前端 未结 4 639
醉话见心
醉话见心 2021-01-31 09:09

I\'m trying to get the hang of Django URL namespaces. But I can\'t find any examples or documentation.

Here is what I have tried.

urls.py:

from d         


        
4条回答
  •  生来不讨喜
    2021-01-31 09:44

    I realize the solution below violates the DRY principal as you have to create essentially duplicate url config files for foo and bar, however I think it should work.

    urls.py:

    from django.conf.urls.defaults import *
    
    urlpatterns = patterns('',
        (r'^foo/', include('sub_urls_foo')),
        (r'^bar/', include('sub_urls_bar')),            
    )
    

    sub_urls_foo.py:

    from django.conf.urls.defaults import patterns, url
    from views import view1
    
    urlpatterns = patterns('views',
        url(r'^(?P\d+)/$', view1, 'view1_foo', {'namespace': 'view1_foo'})
    )
    

    sub_urls_bar.py:

    from django.conf.urls.defaults import patterns, url
    from views import view1
    
    urlpatterns = patterns('views',
        url(r'^(?P\d+)/$', view1, 'view1_bar', {'namespace': 'view1_bar'})
    )
    

    views.py:

    from django.shortcuts import render_to_response
    
    def view1(request, view_id, namespace):
        return render_to_response('view1.html', locals())
    

    And then for the template use this:

    {% url namespace 3 %}
    

    I haven't tested the idea of using a variable in the name section of the {% url %} tag, but I think it should work.

提交回复
热议问题