Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a template exists in Django?

Tags:

python

django

What is the most efficient way to check if a template exists in Django? I was thinking of catching the TemplateDoesNotExist exception, but maybe there is a more Djangoistic way to do it?

Thanks for your help!

like image 934
charlax Avatar asked Apr 16 '11 22:04

charlax


3 Answers

If your intention is to use a template if it exists and default to a second template, you would better use select_template:

django.template.loader.select_template(['custom_template','default_template'])

This will load the first existing template in the list.

like image 129
bformet Avatar answered Oct 21 '22 05:10

bformet


I don't think you'll be able to do this without catching this exception, but you could use django.template.loader.get_template(template_name) in your try statement instead of a optimist call of render_to_response. (If you are not already doing this...)

like image 28
Fábio Diniz Avatar answered Oct 21 '22 06:10

Fábio Diniz


Here is what I implemented, which goes off of Fabio's answer. I don't know if this is the best way to do this, but it works as expected for me.

from django.views.generic import TemplateView
from django.http import Http404
from django.template.loader import get_template
from django.template import TemplateDoesNotExist
from absolute.menu.models import Menu # specific to my app

class BasicPublicView(TemplateView):
    model = Menu #specific to my app

    def dispatch(self, request, *args, **kwargs):
        try:
            self.template_name = request.path[1:] + '.html'
            get_template(self.template_name)
            return super(BasicPublicView, self).dispatch(request, *args, **kwargs)
        except TemplateDoesNotExist:
            raise Http404

This allows me to dynamically pull a template from the templates directory if the template exists. For example, http://example.com/products/keyboards will attempt to fetch the template /templates/products/keyboards.html

like image 11
Zbigniew Jasek Avatar answered Oct 21 '22 06:10

Zbigniew Jasek