Hello.
Does someone know if it is possible to define the readonly_fields of a ModelAdmin based on a condition ? My objective is to make some fields readonly on the admin change view if a field (validation) of the instance is set to True
Model
class NCF(models.Model):
name = models.CharField(max_length=255)
description = models.CharField(max_length=255)
validation = models.BooleanField(default=False)
How can I access the model instance to make a condition ?
Idea of what I would like to achieve in the Admin
@admin.register(NCF)
class NCFAdmin(admin.ModelAdmin):
obj = *model_instance*
if obj.validation:
readonly_fields = ["name", "description"]
...
Thanks for your help
There’s the get_readonly_fields
function you can override that will give you the option to dynamically change the readonly_fields
.
2 Likes
For anyone interested here is how I did.
Note that do not declare the readonly_fileds and in the get_readonly_fields() I simply retrun the list of fields I want to be readonly.
In this exeample I want to change the readonly fields when the instance already exists and his field inspector_validation has been set to True…
@admin.register(Ncf)
class NCFAdmin(admin.ModelAdmin):
list_display = ['_ncf_number', '_statement_link', 'date']
change_form_template = 'admin/ncfs/change_form_with_custom_cancel_validate.html'
raw_id_fields = ['certificate']
...
def get_readonly_fields(self, request, obj=None):
if obj and obj.inspector_validation:
return ["certificate", "report_number", 'inspector', 'inspector_validation', "parent",
"child", 'severity', 'status', 'date']
return ["report_number", 'inspector_validation', "parent", "child", 'inspector', 'status']
...
Hope this help someone