简体   繁体   中英

How to hide the column assigned to "list_display" and "list_display_links" for "list_editable" in Django?

I have Person model below:

# "store/models.py"

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)

Then, I assigned "first_name" and "last_name" to list_display and list_editable to make them editable as shown below:

# "store/admin.py"

from django.contrib import admin
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    list_display = ("first_name", "last_name") # Here
    list_editable = ("first_name", "last_name") # Here

Then, I got the error below:

ERRORS: <class 'store.admin.PersonAdmin'>: (admin.E124) The value of 'list_editable[0]' refers to the first field in 'list_display' ('first_name'), which cannot be used unless 'list_display_links' is set.

So, I assigned "id" to list_display and list_display_links as shown below:

# "store/admin.py"

from django.contrib import admin
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):         # Here
    list_display = ("first_name", "last_name", "id")
    list_editable = ("first_name", "last_name")
    list_display_links = ("id", ) 
                        # Here

Then, the error was solved and 3 columns were displayed as shown below. Now, I want to hide the 3rd column "ID" which I don't need:

在此处输入图像描述

So, how can I hide the 3rd column "ID" ?

You can create the custom column "hidden" with hidden() then can rename it with @admin.display(description="") then can assign it to list_display and list_display_links as shown below:

# "store/admin.py"

from django.contrib import admin
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):           # Here
    list_display = ("first_name", "last_name", "hidden")
    list_editable = ("first_name", "last_name")
    list_display_links = ("hidden", )
                          # Here
                   
    @admin.display(description="") # Here
    def hidden(self, obj):
        return "" 

Then, you can display only 2 columns which you need as shown below:

在此处输入图像描述

Set list_display_links = None in modeladmin class.

from django.contrib import admin
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    list_display = ("first_name", "last_name")
    list_editable = ("first_name", "last_name")
    list_display_links = None

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