Stryker
Stryker

Reputation: 6130

How to conditionally show fields in django admin if there is a value?

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.

Upvotes: 12

Views: 11294

Answers (1)

Eugene Prikazchikov
Eugene Prikazchikov

Reputation: 1904

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/3.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_fields

Upvotes: 28

Related Questions