Setting up self.exclude does, as @ steve-ike mentions, make the whole SubSectionAdmin singleton change its exclude property. Singleton is a class that will use the same instance each time an instance of the class is created, so an instance is created only the first time the constructor is used, and subsequent use of the constructor returns the same instance. A more detailed description can be found on the wiki page. This means that if you write code to exclude the field when changing, it will matter that if you first add the element, it will be there, but if you open the element for change, this field will be excluded for your next visits to the add page .
The easiest way to achieve the behavior of each request is to use get_fields and check the obj argument, which is None if we add an object, and an instance of an object if we change an object. The get_fields method is available from Django 1.7.
class SubSectionAdmin(admin.ModelAdmin): def get_fields(self, request, obj=None): fields = super(SubSectionAdmin, self).get_fields(request, obj) if obj:
Update:
Note that get_fields may return a tuple, so you may need to convert fields to a list to remove items. You may also encounter an error if the name of the field you are trying to delete is not in the list. Therefore, in some cases, when you have other factors that exclude fields, it is better to create a set of exceptions and delete using a list comprehension:
class SubSectionAdmin(admin.ModelAdmin): def get_fields(self, request, obj=None): fields = list(super(SubSectionAdmin, self).get_fields(request, obj)) exclude_set = set() if obj:
Alternatively, you can also do a deepcopy result in the get_fieldsets method, which in other cases can give you access to a better context to exclude material. Most obviously, this will be useful if you need to act with the name fieldset. Also, this is the only way to go if you really use fields , as this will omit the get_fields call.
from copy import deepcopy class SubSectionAdmin(admin.ModelAdmin): def get_fieldsets(self, request, obj=None): """Custom override to exclude fields""" fieldsets = deepcopy(super(SubSectionAdmin, self).get_fieldsets(request, obj))