10👍
I would say it’s a feature.
When field is set to readonly, Django uses display_for_field
function which hardcodes the result, you can’t customize it.
Another approach would be not to set the field as readonly and override formfield_for_dbfield
, an undocumented ModelAdmin
method and act accordingly to your needs.
8👍
An alternative and more flexible solution is to set the “disabled” attribute of those fields you want to render in read-only mode, overriding the get_form(...)
method of your admin class:
def get_form(self, *args, **kwargs):
form = super(SupplierAdmin, self).get_form(*args, **kwargs)
for field_name in self.fake_readonly_fields:
form.base_fields[field_name].disabled = True
return form
note that I take the name of readonly fields not from the usual self.readonly_fields
but from a different array that I named self.fake_readonly_fields
, in order to avoid name overlaps
The limit of the proposed solution (using formfield_for_dbfield
) is that in that way you render at the same way all the database fields of a given type, wether it should be read-only or not. That way works if your entire form should be read-only, but if you deals with forms that are half read-only and half not, it is better to rely on the disabled
attribute.
Further details on my answer here: django modeladmin, readonly_fields and boolean fields
- Method in Django to display all attributes' values belonging to a created object?
- Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
- Set default value for dropdown in django forms