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.
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.
Since we have not specified a
model, we need to tell Django how to process the slug and a pk URL keyword.
Since we do not have a
modelproperty specified, Django should complain automatically if this method is not overridden by you. Here, you return a
QuerySet— by default, Django tries to find the default model manager and return its
all()query. You could do something similar.
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.