finiteautomata
finiteautomata

Reputation: 3813

Django url dispatcher and implicit namespace resolution

I'm using django 1.4 on a project, and I want to use a template across the views of many apps. My urls.py looks like

urlpatterns = patterns('',
    url(r'^canvas/', include('canvas.urls', namespace="canvas")),
    url(r'^checkin/', include('checkin.urls', namespace="checkin")),
    url(r'^show/', include('facebook_tab.urls', namespace="show")),

My canvas/urls.py

from django.conf.urls import patterns, url
from canvas.views import AllShowsView

urlpatterns = patterns('',
    url(r'^shows/$', AllShowsView.as_view(), name='shows'),
)

My facebook_tab/urls.py

from django.conf.urls import patterns, url
from facebook_tab.views import AllShowsView
urlpatterns = patterns('',
    url(r'^shows/$', AllShowsView.as_view(), name='shows'),    
)

And I would like to use a template in such a way that I don't have to refer to the current namespace when using {% url shows %}.

I tried passing current_app to the Context dictionary with no success. Also it doesn't work when I try to do something like reverse("shows", current_app="canvas"). Official documentation is not quite clear about it.

Upvotes: 1

Views: 253

Answers (2)

finiteautomata
finiteautomata

Reputation: 3813

What I've finally done was using url from future as @lalo suggested, and adding both app and instance namespacing to my urls.py

urlpatterns = patterns('',
url(r'^canvas/', include('canvas.urls', app_name="myapp", namespace="canvas")),
url(r'^checkin/', include('checkin.urls', app_name="myapp", namespace="checkin")),
url(r'^show/', include('facebook_tab.urls', app_name="myapp", namespace="facebook_tab")),

Then, from my views I set my current_app as:

return render(request, self.template_name, context, current_app="canvas")

And from my generic template:

{% load url from future %}
{% url 'myapp:shows'%}

That last url would resolve to 'canvas:shows' or 'facebook_tab:shows' depending on the namespace set on current_app.

I read the official docs and I don't already get the difference between application namespace and instance namespace clearly, but I managed to get it to work.

Upvotes: 0

Leandro
Leandro

Reputation: 2247

Importing url from future in your template should work:

 #At the top of the template
 {% load url from future %}

 #Somewhere in your template
 {% url "canvas:shows" %}.

See here: https://docs.djangoproject.com/en/1.4/topics/http/urls/#url-namespaces and https://docs.djangoproject.com/en/1.4/ref/templates/builtins/#url

Upvotes: 2

Related Questions