Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading