在DetailView中,如何根据模型中的字段选择模板?

huangapple go评论79阅读模式
英文:

How to choose template in DetailView based on a field of the model shown?

问题

我有一个带有选择字段的模型:

type = models.CharField(choices=TYPE_CHOICES,
                            max_length=1, default=UNSET, db_index=True)

根据类型,我想在基于类的DetailView中显示不同的模板:

class AlbumDetailView(DetailView):
[...]

目前,我通过设置以下方式来设置模板:

template_name = 'bilddatenbank/album_detail.html'

但是这样就无法访问模型字段的值。我该在哪里设置模板以便访问模型?

谢谢。

英文:

I have a model with a choice field:

type = models.CharField(choices=TYPE_CHOICES,
                            max_length=1, default=UNSET, db_index=True)

Depending on the type I'd like to show a different template in the class based DetailView:

class AlbumDetailView(DetailView):
[...]

Currently I have set the template by setting:

 template_name = 'bilddatenbank/album_detail.html'

But then it's not possible to access the value of the model field. Where can I can set the template while having access to the model?

Thank you.

答案1

得分: 1

你可以重写get_template_names方法,如下所示:

class AlbumDetailView(DetailView):
    model = Album
    template_name = 'bilddatenbank/album_detail.html'

    def get_template_names(self):
        if self.object.type == 't':  # 特殊类型
            return ('bilddatenbank/other_template.html',)
        return super().get_template_names()

希望这对你有帮助。

英文:

You can override the get_template_names method, so:

<pre><code>class AlbumDetailView(DetailView):
model = Album
template_name = 'bilddatenbank/album_detail.html'

def &lt;b&gt;get_template_names&lt;/b&gt;(self):
    if self.object.type == &#39;t&#39;:  # special type
        return (&#39;bilddatenbank/&lt;i&gt;other_template&lt;/i&gt;.html&#39;,)
    return super().get_template_names()&lt;/code&gt;&lt;/pre&gt;

huangapple
  • 本文由 发表于 2023年5月25日 22:23:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76333357.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定