Home > Software design >  Django how to make a basemodel admin general
Django how to make a basemodel admin general

Time:11-15

Here I created a baseadmin model to use in all of my admin models:

class BaseAdmin(admin.ModelAdmin):
    base_readonly_fields = ('created', 'updated','removed')

    def get_readonly_fields(self, request, obj=None):
        if self.readonly_fields:
            return tuple(self.readonly_fields)   self.base_readonly_fields

        else:
            return self.base_readonly_fields


@admin.register(models.Example)
class Example(BaseAdmin):
    list_display = ['id', 'name', 'sf_id', ]

The problem with BaseAdmin is sometimes some models don't have the 'removed' or 'updated'. That's why I get an error.

So I want to make the baseadmin general, if the field exits this will make it readonly like it is on the baseadmin, otherwise and if there is not such field this will just pass and won't rise any error. Any idea how to check this and make the baseadmin more flexable?

CodePudding user response:

One way to do this is to override the base_readonly_fields in the class Example and remove them from the base_readonly_fields.

So, Some admin classes you define that doesn't have those fields needs to override the base_readonly_fields.

This is only worth the trouble if you have more admin classes that have those read_only_fields in them then class that don't have those fields.

If more admin classes don't have the read_only fields, then you should remove them from them base and add them the same way by overriding the base_readonly_fields and adding them there.

CodePudding user response:

Inherit them separately.

class BaseAdmin(admin.ModelAdmin):
    base_readonly_fields = ('created',)

    def get_readonly_fields(self, request, obj=None):
        if self.readonly_fields:
            return tuple(self.readonly_fields)   self.base_readonly_fields

        else:
            return self.base_readonly_fields

class BaseAdminWithUpdateRemoveField(BaseAdmin):
    base_readonly_fields = ('created', 'updated', 'removed')

@admin.register(models.ExampleUpdateRemoveField)
class ExampleWithUpdateRemoveField(BaseAdminWithUpdateRemoveField):
    list_display = ['id', 'name', 'sf_id', ]

@admin.register(models.Example)
class Example(BaseAdmin):
    list_display = ['id', 'name', 'sf_id', ]
  • Related