Mohl
Mohl

Reputation: 415

Django 1.8 check if template exists in view

Is there a better way to check if a template exists in django 1.8?

Currently, I am doing this in views.py:

def get_template_names(self):
    try:
        get_template(self.get_template_name())
        return self.get_template_name()
    except TemplateDoesNotExist:
        return self.get_fallback()

I do not feel entirely comfortable to load the template in order to check if I can load the template.

Upvotes: 2

Views: 655

Answers (1)

Alasdair
Alasdair

Reputation: 308909

The method get_template_names() is meant to return a list of templates. So if calculating get_fallback() is not expensive, you can call it and include it in the list. Django will use the first template in the list that exists to render the template.

def get_template_names(self):
    return ['default_template_name.html', self.get_fallback()]

Upvotes: 4

Related Questions