简体   繁体   中英

Change field name in django admin

I am customizing django admin and I would like to change the display name of my fields. I think the answer is here but I can't find it. I already change the table name thanks to Meta class. I have also ordered fields, gathered them, collapsed them...

What I was looking for is :

name = models.CharField(max_length=200, verbose_name="Nom")

Thanks anyway for your help !

Setting verbose_name on the model field, as in the accepted answer , does work, but it has some disadvantages:

  • It will also affect the field label in non-admin forms, as mentioned in the comment

  • It changes the definition of the model field, so it results in a new migration

If you only want to change the display name of the field on the admin site, you could either override the entire form, as suggested in this other answer , or simply modify the form field label by extending ModelAdmin.get_form() , as in the example below:

class MyModelAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, change=False, **kwargs):
        form = super().get_form(request, obj, change, **kwargs)
        form.base_fields['my_model_field_name'].label = 'new name'
        return form

Note that this does not work if the field is in readonly_fields (at least in Django 2.2.16), because the field will be excluded form.base_fields (see source ). In that case, one option would be to remove the field from readonly_fields and disable it instead, by adding another line inside get_form() :

form.base_fields['my_model_field_name'].disabled = True

Look at Field.label. See this: https://docs.djangoproject.com/en/dev/ref/forms/fields/#label

Basically, it's

class MyForm(forms.Form):
    name = forms.CharField(label='My Name')

But that requires extending the admin, which may be more than you want to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM