How to register inherited sub class in admin.py file in django?

北战南征 提交于 2021-01-29 07:21:06

问题


  • Project Name : fusion
  • App Name : admin_lte
  • Python 3.7
  • Django 2
  • MySql

Question is "I want to register sub model in django admin-panel",when i write code for model registration in admin.py file that time occurred below error.

django.core.exceptions.ImproperlyConfigured: The model Device is abstract, so it cannot be registered with admin.

NOTE : I used multiple separated model file.

device.py (Model File)

from django.db import models

class Device(models.Model):
device_type = models.CharField(max_length=100,blank=False)
price = models.IntegerField()
status =  models.CharField(max_length=10, default="SOLD")
issues = models.CharField(max_length=100, default="No Issues")

class Meta:
    abstract = True

def __str__(self):
    return 'Device_type:{0} Price:{1}'.format(self.device_type,self.price)


#Inheritance Concept
class Laptop(Device):
   pass
   class Meta:
       db_table = "laptop"

class Desktop(Device):
   pass
   class Meta:
       db_table = "Desktop"

class Mobile(Device):
    pass
    class Meta:
        db_table = "Mobile"

__init__.py File

from django_adminlte.models.employee import Employee
from django_adminlte.models.device import Device

admin.py

from django.contrib import admin
from.models import Employee
from.models import Device

admin.site.register (Employee)
admin.site.register (Device)

I want to show sub model (Desktop,Laptop,Mobile) in admin panel so admin can add some data from admin panel.


Project Structure Image :


回答1:


I can see in your code Device is a abstract model. So, we should not register it because abstract models do not have associated tables in databases.

from django.contrib import admin
from .models import Employee, Laptop, Mobile, Desktop

admin.site.register(Employee)
admin.site.register(Laptop)
admin.site.register(Mobile)
admin.site.register(Desktop)


来源:https://stackoverflow.com/questions/54514324/how-to-register-inherited-sub-class-in-admin-py-file-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!