Is there a way to detect unused templates in a Django project?
Before Django 1.3, that would have been possible with a simple string-matching function like this one. But since 1.3, there are generic class based views that automatically generate a template_name, if you don’t override it (e.g. DetailView).
Also, if you override 3rd party module templates, those templates aren’t used anywhere directly in your views.
Maybe it could be done by crawling all URL definitions, loading the corresponding views and getting the template_name from them?
It’s not possible to detect unused templates for certain, even in the absence of generic views, because you can always write code like this:
So even prior to Django 1.3 the django-unused-templates application you linked to could only have worked for projects that respected some kind of discipline about the use of templates. (For example, always having a string literal as the template argument to functions like
get_templateandrender_to_response.)Loading all the views wouldn’t be sufficient either: a view may use different templates under different circumstances:
And of course templates may not be used by views at all, but by other parts of the system (for example, e-mail messages).