pythondjangolabeldjango-admindisplaylist

How to change the label in display_list of a field in the model in django admin?


I have a model with some fields with a verbose_name. This verbose name is suitable for the admin edit page, but definitively too long for the list page.

How to set the label to be used in the list_display admin page?


Solution

  • You can create custom columns.

    For example, there is Person model below:

    # "models.py"
    
    from django.db import models
    
    class Person(models.Model):
        name = models.CharField(max_length=30)
        age =  models.IntegerField()
    

    Now, you can create the custom columns "my_name" and "my_age" with my_name() and my_age() and can rename them with @admin.display as shown below:

    @admin.register(Person)
    class PersonAdmin(admin.ModelAdmin):
        list_display = ("my_name", "my_age") 
                      # "my_name" and "my_age" need to be assigned
    
        @admin.display(description='My name')
        def my_name(self, obj):      # ↑ Displayed
            return obj.name
    
        @admin.display(description='My age')
        def my_age(self, obj):       # ↑ Displayed
            return obj.age
    

    Then, MY NAME, MY AGE and the values of "name" and "age" fields are displayed as shown below:

    enter image description here

    Of course, you can assign "name" and "age" fields to list_display in addition to the custom columns "my_name" and "my_age" as shown below:

    @admin.register(Person)
    class PersonAdmin(admin.ModelAdmin):
        list_display = ("my_name", "my_age", "name", "age") 
                                              # ↑ Here ↑
    
        @admin.display(description='My name')
        def my_name(self, obj):
            return obj.name
    
        @admin.display(description='My age')
        def my_age(self, obj):
            return obj.age
    

    Then, NAME, AGE and the values of "name" and "age" fields are displayed as shown below:

    enter image description here