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


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.

>Solution :

You can override the get_template_names method, so:

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

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

Leave a ReplyCancel reply