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
Here is one solution I came up with.
views.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
def render_response_context(view, locals):
request = locals["request"]
app = "bar" if request.META["PATH_INFO"].lower().startswith("/bar") else "foo"
return render_to_response(view, locals,
context_instance=RequestContext(request, current_app=app))
def view1(request, view_id):
return render_response_context('view1.html', locals())
view1.html:
{% load extras %}
{% namespace_url view1 3 %}
extras.py:
from django import template
from django.core.urlresolvers import reverse
register = template.Library()
@register.tag
def namespace_url(parser, token):
tag_name, view_string, arg1 = token.split_contents()
return NamespaceUrlNode(view_string, arg1)
class NamespaceUrlNode(template.Node):
def __init__(self, view_string, arg1):
self.view_string = view_string
self.arg1 = arg1
def render(self, context):
return reverse("%s:%s" % (context.current_app, self.view_string), args=[self.arg1])
Basically I made sure to always pass the current_app context as either "foo" or "bar", which I calculate manually by looking at the request URL. Then I use a custom tag that resolves a URL based on current_app.
It's not very generic; "foo" and "bar" are hard-coded, and the tag can only take exactly one argument. Even with those issues fixed, this seems like a hack.