[Django]-How to check if a template exists in Django?

28👍

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…)

42👍

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.

11👍

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

Leave a comment