django - 如何在基于 Django 类的 View 中更改模板

如果我有一个基于类的 View ,例如:

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

    def get_queryset(self):
        #some stuff

如何根据查询更改 template_name?我想做类似的事情:

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

但是你不能访问get_queryset之前的请求。 或者也许有更简单的方法来实现相同的行为?

最佳答案

您可以覆盖 .get_template_names() method [Django-doc] , 并返回匹配的模板名称,所以:

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

.get_template_names() 应该返回模板名称的 iterable。如果模板不存在,Django 将遍历列表,从而呈现第一个存在的可迭代模板。在这种情况下,我们可以返回一个单例列表,其中包含 Django 应该尝试呈现的唯一模板。

https://stackoverflow.com/questions/68320830/

相关文章:

rust - 如何正确处理 Warp 路由的错误

python - 我的损失函数在训练期间没有得到更小的值

c - 为什么 GTK 4 报告 "assertion ' GTK_IS_WIDGET(部件 )'

sql - 如何获得日期 + 时间的确定性计算值

sass - Stylelint 禁用规则, "no-descending-specificity"

reactjs - 如何在 primereact 中拥有主题切换器

python - 多次拟合时 keras fit() 的历史

javascript - A 帧动画框在特定区域随机移动

python - numpy 中如何实现多维数组切片/索引?

kubernetes - 部署后如何在 kubernetes 中删除 Traefik 2.0 中间件