在django admin中显示模型的_unicode__

时间:2022-09-06 20:16:56

I would like to display the model's username in Django Admin interface but not very sure how to do it..

我想在Django Admin界面中显示模型的用户名,但不太确定如何操作..

The models.py:

    class Adult(models.Model):    
        user = models.OneToOneField(User)
        fullname = models.CharField(max_length=100,
                                    blank=True)
        def __unicode__(self):
            return self.user.username

Admin.py:

    class AdultAdmin(admin.ModelAdmin):
        list_display = ('??', 'Student_Name',)
        search_fields = ['??',]

    admin.site.register(Adult, AdultAdmin)

What should go inside the ?? above ? I would like to display the unicode or the self.user.username? How do i do it? Need some guidance...

里面应该怎么办?以上 ?我想显示unicode或self.user.username?我该怎么做?需要一些指导......

1 个解决方案

#1


32  

From the list_display documentation there are four things you can add there:

从list_display文档中可以添加四件事:

  1. A field
  2. 一个字段
  3. Some method (a callable) that accepts one variable that is the instance for which the row is being displayed.
  4. 一些接受一个变量的方法(可调用),该变量是显示该行的实例。
  5. A string that is the name of a method or attribute defined in the model class.
  6. 一个字符串,它是模型类中定义的方法或属性的名称。
  7. A string that is the name of a method that is defined in ModelAdmin.
  8. 一个字符串,它是ModelAdmin中定义的方法的名称。

For your case we need #3 for list_display.

对于你的情况,我们需要#3 for list_display。

For search_fields its easier as you can use follow notation (__) to do lookups.

对于search_fields,它更容易,因为您可以使用跟随符号(__)进行查找。

In the end we come up with this:

最后我们想出了这个:

class AdultAdmin(admin.ModelAdmin):
    list_display = ('__unicode__', 'Student_Name',)
    search_fields = ['user__username']

#1


32  

From the list_display documentation there are four things you can add there:

从list_display文档中可以添加四件事:

  1. A field
  2. 一个字段
  3. Some method (a callable) that accepts one variable that is the instance for which the row is being displayed.
  4. 一些接受一个变量的方法(可调用),该变量是显示该行的实例。
  5. A string that is the name of a method or attribute defined in the model class.
  6. 一个字符串,它是模型类中定义的方法或属性的名称。
  7. A string that is the name of a method that is defined in ModelAdmin.
  8. 一个字符串,它是ModelAdmin中定义的方法的名称。

For your case we need #3 for list_display.

对于你的情况,我们需要#3 for list_display。

For search_fields its easier as you can use follow notation (__) to do lookups.

对于search_fields,它更容易,因为您可以使用跟随符号(__)进行查找。

In the end we come up with this:

最后我们想出了这个:

class AdultAdmin(admin.ModelAdmin):
    list_display = ('__unicode__', 'Student_Name',)
    search_fields = ['user__username']