So I've got this insane requirement that says I need to isolate all my django apps under a prefix ... as such
...
Somebody please tell me I've been hitting the crack pipe a bit to hard and that there is a more elegant solution to this silliness, either through Apache ( mod_rewrite? ) or Django.
There is not yet officially introduced and documented but working
feature (The Right Feature!) for making URLs in your templates to
automatically point to your views by their current path. It's called
'reverse URL lookup'. It works by scanning actual regexps in your urlconf.
I've created a template tag that wraps it to be usable in templates:
class URLNode(template.Node):
def __init__(self, view_name, args):
self.view_name = view_name
self.args = args
def render(self, context):
from django.core.urlresolvers import reverse, NoReverseMatch
args = [arg.resolve(context) for arg in self.args]
project_name = settings.SETTINGS_MODULE.split('.')[0]
try:
return reverse(project_name + '.' + self.view_name, args=args)
except NoReverseMatch:
return ''
@register.tag
def url(parser, token):
bits = token.contents.split()
if len(bits) > 2:
args = [parser.compile_filter(arg) for arg in bits[2].split(',')]
else:
args = []
return URLNode(bits[1], args)
The usage is:
{% url app_name.views.artist artist.id %}
I.e. you provide a path to a view and actual parameters that it accepts
and it returns something like '/path/to/your/project/artist/15/'
('artist' and '15' are for example).
It's a bit limited since it works only with positional arguments in
views but not with keyword ones. This is not hard to do in code since
'reverse' function itself already support it. I just couldn't come up
with a nice syntax for a tag :-)
Nice, Ivan! I've been meaning to write something like this...Would you
be willing to contribute it to the framework?
Adrian
--
Adrian Holovaty
holovaty.com | djangoproject.com
Sure, as usually :-) Have you are: http://code.djangoproject.com/ticket/2606
I also added a docstring that may be a bit clumsy and will certainly
require a proof-read.