-
Django URL template tag follow-up
After reading the comments on my last post, about my beefs with Django’s URL template tag, it sounds like I made an assumption that was incorrect: I had understood that the
{% url %}tag is now considered a best practice, and using theget_asbsolute_urlmethod in templates is now considered a less-than-best practice.Turns out, most people agree with me that
Moreget_absolute_urlis still a very valid method of getting the URL for an object’s detail page for use in templates. Sounds like most people are now doing the same thing I do, which is to use the{% url %}tag when it makes sense (for pages not associated with an object, or for views with few or no arguments), and to useget_absolute_urlfor object detail pages -
Django’s URL template tag sucks
I don’t like Django’s
{% url %}template tag, and I’m about to tell you why. But first, let’s have a little history lesson so we understand why the{% url %}tag exists and what problem it attempts to solve.I’ve been involved in Django since the .90 release, or nearly three years. As long as I’ve been working with Django, there’s been a convention which basically says that any model whose instances are represented by a page on the site should get a method called
get_absolute_url, which returns the relative URL to that instance’s page (for now, please ignore the fact thatget_absolute_urlis misnamed and actually returns a URL relative to the root of the site).In the early days, the
Moreget_absolute_urlmethod for a blog entry might have looked like this… -
“Default” templates in Django
Django’s templating system is one of its strongest points, in my opinion, and one of it’s coolest features it the “fallback” system used for locating templates. When used wisely, it can allow for a situation in which you can literally design an entire site by creating only one HTML file.
In Django’s
settings.pyfile, you configure yourTEMPLATE_DIRSvariable. This is simply a Python tuple representing filesystem paths to the locations your templates reside. For example:TEMPLATE_DIRS = ( '/home/jcroft/webapps/django/jeffcroft.com/templates2', '/home/jcroft/webapps/django/jeffcroft.com/templates1', )Here, we’ve got two directories containing templates:
Moretemplates1, andtemplates2. Whenever a Django app attempts to load a template, it will look in these two paths to find it. For example, if your blog application needs a template calledblog/entry_detail.html, it will first look for it in.../templates2/blog/entry_detail.html. If it’s not found, it will “fallback” to.../templates1/blog/entry_detail.html(if it’s still not found, Django will return an error.)
