Register abstract model in admin django 1.6

2019-08-03 06:32发布

问题:

After searching a while i didn't find any clear solution

File: models.py

class BaseModel(models.Model):
    created_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True


class Company(BaseModel):
    company_name = models.CharField(max_length=50, unique=True)

    def __str__(self):
        return self.company_name

File: models.py

from django.contrib import admin
from .models import Company

class CompanyAdmin(admin.ModelAdmin):
    pass

admin.site.register(Company, CompanyAdmin)

I tried the solution here: Django admin model Inheritance is it possible? but nothing works, and the admin is only showing the company_name

回答1:

The reason why those fields are not being showed in the admin, is because of the auto_now and auto_now. What you need to do is adde them explicitly as read-only fields:

admin.py

from django.contrib import admin
from .models import Company

class CompanyAdmin(admin.ModelAdmin):
    readonly_fields = ('created_date', 'modified_date')

admin.site.register(Company, CompanyAdmin)