Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 945
Stryker Avatar asked Oct 31 '16 17:10

Stryker


1 Answers

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

like image 156
Eugene Prikazchikov Avatar answered Oct 12 '22 16:10

Eugene Prikazchikov