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

This is a draft post. Find out more about what that means. Get in touch if this post could use an improvement.

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

My employer is looking to hire a full-time junior Django developer.

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 if 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.

I do recall a certain other CBV not working unless a model was specified, but can’t seem to remember which one it was. If you know such a CBV, I would like to add it here for clarity and completeness. Please let me know!

Join the discussion on Mastodon or Twitter, or write me an email.