Use any model at run-time with a DetailView in Django.

How do you use any model instance with a DetailView? By overriding a couple of methods and leaving the model property unspecified.

This is a part of the 100 Days To Offload challenge.

Django’s Class Based Views (CBVs) are generally great. I ended up in a situation at work recently where I wanted to keep using DetailView, but change which model was used depending on which user was logged in and making this request to the view class.

A few weeks ago, I had left this task incomplete with a TODO marker. On Friday, I was playing catch-up on some of these TODOs. I noticed something interesting.

The sauce.

While looking through the Django source code, I noticed that the DetailView class does not expect a model property to be specified. It does not throw an error if the property is left unspecified.

What this means is one could override a couple of methods and conditionally return a DetailView for whatever object/instance you desire, regardless of the model.

Using this awareness, I was able to do exactly what I needed. I have not included any code snippets since this is not targeted towards complete beginners. However, if you’re reading this and would like a snippet or two, please write me an email.

0

Comment via email.