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!
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.
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...)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With