Django管理屏幕不会按名称显示实体

时间:2015-04-09 16:19:26

标签: python django python-3.x django-models django-admin

The Admin screen

在Django中,我在模型中创建了一个名为User的实体,当我在Admin页面中显示它时,它只显示为User Object而不是id或name,我该如何更改?

如何将其更改为直观的内容?喜欢用户的ID或名称?

models.py显示:

class User(models.Model):
    user_id = models.CharField(primary_key=True, max_length=200)
    name = models.CharField(max_length=200)
    phone_number = models.CharField(max_length=200)
    user_password = models.CharField(max_length=20)
    email = models.CharField(max_length=200)
    category = ( ('A','First AC'), ('B','Second AC'), ('C','Third AC'), ('D','Sleeper') )

此外,为什么类别中的选项不会出现在“添加用户”屏幕上?

Add User

此应用的admin.py [已命名'数据']具有:

from django.contrib import admin    
from data.models import User
admin.site.register(User)

1 个答案:

答案 0 :(得分:3)

在模型中包含__str__ method,返回您要显示的字符串:

class User(models.Model):
    user_id = models.CharField(primary_key=True, max_length=200)
    name = models.CharField(max_length=200)
    phone_number = models.CharField(max_length=200)
    user_password = models.CharField(max_length=20)
    email = models.CharField(max_length=200)
    category = ( ('A','First AC'), ('B','Second AC'), ('C','Third AC'), ('D','Sleeper') )

    def __str__(self):
        return '{}'.format(self.user_id)