英文:
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 <b>get_template_names</b>(self):
if self.object.type == 't': # special type
return ('bilddatenbank/<i>other_template</i>.html',)
return super().get_template_names()</code></pre>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论