I have a django application which is using django.contrib.admin
for administrative tasks.
For one model I now need to add a field which indicates which part of the code each row was created from. I am using readonly_fields
to prevent this value from being changed through the administration interface.
A default value in this field will tell me that the row was either
But I need better granularity than that. In particular I want to be able to distinguish between a row created by code which doesn't know about the field, and a row created through the administration interface.
Is there some way my ModelAdmin
class can specify an initial value for a field mentioned in readonly_fields
?
I found this solution, which appears to work:
class Admin(ModelAdmin):
readonly_fields = ('created_by',)
def save_form(self, request, form, change):
r = super(Admin, self).save_form(request, form, change)
if not change:
assert r.created_by == CREATED_BY_UNKNOWN
r.created_by = CREATED_BY_ADMIN
return r
CREATED_BY_UNKNOWN
and CREATED_BY_ADMIN
are values defined elsewhere in my code.