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 TODO
s. 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.
get_object(self, queryset=None)
Since we have not specified amodel
, we need to tell Django how to process the slug and a pk URL keyword.get_queryset(self)
Since we do not have amodel
property specified, Django should complain automatically if this method is not overridden by you. Here, you return aQuerySet
— by default, Django tries to find the default model manager and return itsall()
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.