Django URL Namespaces and Templates… kind of not pretty

So, I shouldn’t admit it, but I’m a Django beginner. (I’ve done a lot of other frameworks, but Django is new to me.) It has a really nice feature to write URLs for you; you don’t code URLs into the pages, but use a name to find a URL’s associated pattern, and generate based on the pattern. It’s really nice.

It gets less nice when you have multiple apps on the same project, and you start namespacing the URLs. Then, to reverse them, you need to add the namespace to the URL reversal tags:

{% url 'mypoll:detail' question.id %}

Ewww. You really want to use ‘detail’ without the namespacing.

There is a solution, and it’s that the URL reversal has a somewhat complex way of matching the name.

HTTP Reversing URL Namespaces

It says if there’s no match to a namespace, it’ll match to the app name.

So you can use the appname as a kind of generic namespace:

{% url 'polls:detail' question.id %}

Then, you need to add an attribute ‘current_app’ that is set to the app name. That’s when it gets tricky. The example code at the link has one way. Here’s another example, using the tutorial’s example:

class DetailView(generic.DetailView):
    model = Question
    def get(self, request, *args, **kwargs):
        request.current_app = self.request.resolver_match.namespace
        return super(DetailView, self).get(self, request, *args, **kwargs)

There’s a lot of repeated code.

I’m starting to think this is mainly an aesthetic problem, not a real-world problem. There are probably few situations when you want really generic URL reversal.

“Oh well” for now.