Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Django Admin - 设置显示字段


使列表显示更易读

当您将模型显示为列表时,Django 会将每个记录显示为记录对象的字符串表示形式,在我们的例子中是“Member object (1)”,“Member object(2)”等。

要将其更改为更易读的格式,我们有两个选择

  1. 更改字符串表示函数,__str__() Member 模型
  2. 设置 list_details Member 模型的属性

更改字符串表示函数

要更改字符串表示形式,我们必须定义 __str__() Member 模型中的函数 models.py,如下所示

my_tennis_club/members/models.py:

from django.db import models

class Member(models.Model):
  firstname = models.CharField(max_length=255)
  lastname = models.CharField(max_length=255)
  phone = models.IntegerField(null=True)
  joined_date = models.DateField(null=True)

  def __str__(self):
    return f"{self.firstname} {self.lastname}"

这将给我们带来以下结果

定义我们自己的 __str__() 函数不是 Django 功能,而是如何在 Python 中更改对象的字符串表示形式。在我们的 Python 对象教程 中了解更多关于 Python 对象的信息。


设置 list_display

我们可以通过在 admin.py 文件中的 list_display 属性中指定它们来控制要显示的字段。

首先创建一个 MemberAdmin() 类并指定 list_display 元组,如下所示

my_tennis_club/members/admin.py:

from django.contrib import admin
from .models import Member

# Register your models here.

class MemberAdmin(admin.ModelAdmin):
  list_display = ("firstname", "lastname", "joined_date",)
  
admin.site.register(Member, MemberAdmin)

请记住,在 admin.site.register(Member, MemberAdmin) 中添加 MemberAdmin 作为参数。

现在返回浏览器,您应该会得到以下结果


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.