Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change template in Django class based view

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?

like image 834
MattG Avatar asked Nov 16 '25 08:11

MattG


1 Answers

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.

like image 55
Willem Van Onsem Avatar answered Nov 18 '25 01:11

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!