Django: It's DRY, but you can sink your teeth into it
One of Django's core principles is the concept of DRY: Don't Repeat Yourself. Overall, the framework does a fantastic job at forcing you to follow that principle by default (and it's never a bad thing). Here and there, however, we need to add some initiative. I'd like to quickly share one such place: template tag imports. If you have a tag that you use very often, it becomes tedious to put
{% load common_tag_module %}
at the top of every single template. Not only tedious, but what if you need to rename that tag? Or forget to add it? For that reason, we can use a neat and little-known trick to add a tag library to the default tag library for your project. This is how you do it:
from django import template
template.add_to_builtins('project.app.templatetags.common_tag_module')
If you put this in a module that's loaded by default, such as your main urlconf file, you'll have the tags and filters from your custom tag module available in any template, regardless of whether you specifically import it or not. Fantastic!
I use this often for the humanize and sorl.thumbnail tag libraries, as well as some libraries that we use in our own projects. Most often in Django, when you're thinking "Wow, I'm getting tired of typing/copying this all the time", there's already an eloquent way to make your code more DRY - you just need to find it. And when you do, you love Django even more.
If you found this post interesting, you might also like our blog post, Shorter Django Class-based Views Using Lambda Functions
