Home > Mobile >  How to change the label in display_list of a field in the model in django admin
How to change the label in display_list of a field in the model in django admin

Time:11-09

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 ?

CodePudding user response:

It might be possible that you use verbose_name the wrong way, and that you should use help_text=… [Django-doc] instead:

from django.db import models


class MyModel(models.Model):
    name = models.CharField(
        max_length=64,
        help_text='here some long help text that this is about filling in the name',
    )

If you really want to use a different one for the list_display, you can work with a property, like:

from django.contrib import admin
from django.db import models


class MyModel(models.Model):
    name = models.CharField(
        max_length=64,
        verbose_name='Long name for name field',
    )

    @property
    @admin.display(description='Short name', ordering='name')
    def name_display(self):
        return self.name

    @name_display.setter
    def name_display(self, value):
        self.name = value

Then in the ModelAdmin you use the name_display:

from django.contrib import admin


@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    list_display = ['name_display']

CodePudding user response:

You can change the description of the headers in a few different ways. "Description" meaning the table headers of the admin list view.

Please see:

https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display

Which describes several methods to customise the headers in the list display view of the admin pages.

  • Related