How to change label / caption of readonly item in django admin

Viewed 415

I just would like to find an answer of how to change label / caption of readonly item in Django admin.

When the field / form is not readonly then it is rather easy to do like:

class MyModelAdmin(admin.ModelAdmin):
    readonly_fields=(
        'field_ro_1', 
        'field_ro_2', 
    )
    
    def get_form(self, request, obj=None, change=False, **kwargs):
        form = super().get_form(request, obj, change=False, **kwargs)
        form.base_fields['field_xyz'].label = 'This is field XYZ'
        form.base_fields['field_ro_1'].label = 'This is field readonly 1' # this doesn't work for readonly form and causing an error
        return form

But what to do with readonly forms / fields? Thank you so much in advance for the hints.

1 Answers

If your readonly field is a field on the model...

For a field that is already a field on your model, you can do it the same way as you would any other field. Incidentally, a better way of doing this than your method above is using the fields verbose_name attribute:

class MyModel(models.Model):
    ...
    name = models.CharField(
        max_length=255,
        verbose_name="This will be the label"
    )

If your readonly field is a method...

You can set a short_description property on the actual function

class MyModel(models.Model):

    def my_readonly_field(self):
        return "something"
    
    my_readonly_field. short_description = "This will be the label"
class MyModelAdmin(models.Model):
    readonly_fields = ("name", "my_readonly_field", "my_other_readonly_field")

    def my_other_readonly_field(self, obj):
        return "something else"

    my_other_readonly_field.short_description = "Label goes here"

You can read more info in the docs

Related