How do you use Django URL namespaces?

前端 未结 4 650
醉话见心
醉话见心 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:56

    There seems to be no direct way to do it. I would use a similiar solution as you introduced using a template tag, though I found a more generic way. I used the fact that you can pass optional parameters in your url conf, so you can keep track of the namespace:

    #urls.py
    from django.conf.urls import defaults
    
    urlpatterns = defaults.patterns('',
        defaults.url(r'^foo/', include('sub_urls', namespace='foo', app_name='myapp'), 
        kwargs={'namespace':'foo'}),
        defaults.url(r'^bar/', include('sub_urls', namespace='bar', app_name='myapp'),
        kwargs={'namespace':'bar'}),      
    )
    

    That also violates the DRY principle, but not much though :)

    Then in your view you get the namespace variable (sub_urls.py would be the same):

    #views.py
    from django import shortcuts
    
    def myvew(request, namespace):
        context = dict(namespace=namespace)
        return shortcuts.render_to_response('mytemplate.html', context)
    

    Later you just need a simple tag you pass your namespace variable and view name to:

    #tags.py
    from django import template
    from django.core import urlresolvers
    
    register = template.Library()
    
    def namespace_url(namespace, view_name):
       return urlresolvers.reverse('%s:%s' % (namespace, view_name, args=args, kwargs=kwargs)))
    register.simple_tag(namespace_url)
    

    and use it in the template (make sure to pass your view name as a string, and not as a template variable):

    
    {% load tags %}
    {% namespace_url namespace "view1"%}
    

    Thanks for your hint btw.. I was looking for sth. like this.

提交回复
热议问题