How to conditionally show fields in django admin i

2020-03-03 06:35发布

问题:

in admin.py file I have a

 fields = ('name', 'description', ('created_by','created', ),('updated_by', 'updated'))

How can I only show created, created_by if is NON blank. When I about to create a new records, created_by, created, updated_by and updated is blank and I don't need to show them.

Only when I save the records, I like to show these fields in django admin.

回答1:

Try setting fields dynamically via get_fields method. Like this:

class MyAdmin(ModelAdmin):
    def get_fields(self, request, obj=None):
        if obj is None:
            return ('name', 'description')
        return ('name', 'description', ('created_by','created', ),('updated_by', 'updated'))

https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_fields