Suppose I have car - suv/bus models.
I'd like to list all cars in the django admin (with name attribute).
When user clicks one of the car, it would go to the appropriate detail page of either suv or bus model.
How do I create a such admin list page?
class Car:
name = models.CharField()
class Meta:
abstract=True
class Suv(Car):
pass
class Bus(Car):
pass
Not sure this is the best approach, but sharing my solution here.
First, create a Database View
then create non-manged model
then, from admin page, change the links based on subclass types.
volla you have a admin that shows multiple subclasses at one list.
You need to make your
Car
not an abstract model, as you have to have some base table for your vehicles.But here the easy things end. The admin doesn't have a built-in solution for your task. I suggest you overriding at least the
CarAdmin.get_form()
andCarAdmin.get_queryset()
methods, though I'm not sure they are the only ones you have to customize.eugene's answer took me to the right direction. Thank you.
I'm not aware if there is a better way either, but in my case this approach solved the problem.
I already had a base class (
Project
) with some generic fields (SportProject
and others), and specific classes that extends Project with their fields, and I wanted to have a single list of project, but wanted to have specific edit form for each project type.In app/admin.py file, I did:
In my model
Project
, I have achildren
property that returns the children instance (SportProject
for instance). Not sure if there is another way to have this structure in Django.I also had all classes registered in django-admin (
Project
and all children, asSportProject
), to have django-admin pages for those classes. Thus, I'm using django-modeladmin-reorder to hide undesired links on django-admin main page.Hope it helps someone.
I think this answer is applicable. ModelAdmin needs to know foreign key entries will be readonly, specified in a tuple called readonly_fields.
Using the problem that brought me here and there, I have (models.py):
And (admin.py):
Hope this proves useful to future searchers.