If there a way to detect if information in a model is being added or changed.
If there is can this information be used to exclude fields.
Some pseudocode to illustrate what I'm talking about.
class SubSectionAdmin(admin.ModelAdmin):
if something.change_or_add = 'change':
exclude = ('field',)
...
Thanks
orwellian's answer will make the whole SubSectionAdmin singleton change its exclude property.
A way to ensure that fields are excluded on a per-request basis is to do something like:
which will just inform the Form to exclude those extra fields.
Not sure how this will behave given a required field being excluded...
Setting
self.exclude
does as @steve-pike mentions, make the wholeSubSectionAdmin
singleton change its exclude property. A singleton is a class that will reuse the same instance every time the class is instantiated, so an instance is only created on the first use of the constructor, and subsequent use of the constructor will return the same instance. See the wiki page for a more indept description. This means that if you write code to exclude the field on change it will have the implication that if you first add an item, the field will be there, but if you open an item for change, the field will be excluded for your following visits to the add page.The simplest way to achieve a per request behaviour, is to use
get_fields
and test on theobj
argument, which isNone
if we are adding an object, and an instance of an object if we are changing an object. Theget_fields
method is available from Django 1.7.Update:
Please note that
get_fields
may return a tuple, so you may need to convertfields
into a list to remove elements. You may also encounter an error if the field name you try to remove is not in the list. Therefore it may, in some cases where you have other factors that exclude fields, be better to build a set of excludes and remove using a list comprehension:Alternatively you can also make a
deepcopy
of the result in theget_fieldsets
method, which in other use cases may give you access to better context for excluding stuff. Most obviously this will be useful if you need to act on the fieldset name. Also, this is the only way to go if you actually use fieldsets since that will omit the call toget_fields
.The approach below has the advantage of not overriding the object wide
exclude
property; instead it is reset based on each type of request