Reputation: 185
As subject, i want to hide some fields ONLY when users enter the 'CREATE' admin page for specific model.
I know that change list_display can hide fields in admin page, but it's a global setting which will take affect not only in 'CREATE' admin page, but also in 'UPDATE' admin page.
Upvotes: 5
Views: 1088
Reputation: 839
Django now has a get_exclude
method on ModelAdmin for excluding fields programmatically.
It takes the current request and the object (if any) as argument. In your case, the object argument will be none if it's a "create" page so you can use that like so:
class MyModelAdmin(admin.ModelAdmin):
def get_exclude(self, request, obj=None):
excluded = super().get_exclude(request, obj) or [] # get overall excluded fields
if not obj: # if it's a create, so no object yet
return excluded + ['extra_field_to_exclude']
return excluded # otherwise return the default excluded fields if any
Upvotes: 1
Reputation: 185
Copied from Exclude fields in Django admin for users other than superuser
def get_fieldsets(self, request, obj=None):
fieldsets = super(MediaAdmin, self).get_fieldsets(request, obj)
if not obj:
fieldsets = (
(u'other', {
'fields': ('media_public_id',)
}),
)
return fieldsets
Upvotes: 2
Reputation: 7787
@admin.register(User)
class UserProfileAdmin(UserAdmin):
def get_fields(self, request, obj=None):
fields = super(UserProfileAdmin, self).get_fields(request, obj)
for field in fields:
if field == 'some_field_name' and obj is None:
continue
yield field
Upvotes: 3