How to change template in Django class based view

1.2k views Asked by At

If i have a class based view like:

class equipmentdashboardView(LoginRequiredMixin,ListView):
    context_object_name = 'equipmentdashboard'
    template_name = 'equipmentdashboard.html' 
    login_url = 'login'

    def get_queryset(self):
        #some stuff

How can I change the template_name depending on a query? I want to do something like:

class equipmentdashboardView(LoginRequiredMixin,ListView):
    context_object_name = 'equipmentdashboard'
    if self.request.user.PSScustomer.customerName == 'Customer X':
        template_name = 'equipmentdashboard_TL.html' 
    else:
        template_name = 'equipmentdashboard.html' 
    login_url = 'login'

    def get_queryset(self):
            #some stuff

But you can't access the request before the get_queryset. Or maybe there is an even simpler way of achieving the same behavior?

1

There are 1 answers

0
willeM_ Van Onsem On BEST ANSWER

You can override the .get_template_names() method [Django-doc], and return the template name(s) that match, so:

class equipmentdashboardView(LoginRequiredMixin,ListView):
    context_object_name = 'equipmentdashboard'
    login_url = 'login'
    
    def get_template_names(self):
        if self.request.user.PSScustomer.customerName == 'Customer X':
            return ['equipmentdashboard_TL.html']
        else:
            return ['equipmentdashboard.html']

.get_template_names() should return an iterable of template names. Django will enumerate through the list if the template does not exists, and thus render the first template of the iterable that does exist. In this case we can thus return a singleton list with the only template that Django should try to render.