[英]Access to user data from profile in admin.py
I'm trying to create an admin configuration to my new Profil class. 我正在尝试为新的Profil类创建管理员配置。
class Profil(models.Model):
user = models.OneToOneField(User)
birthdate = models.DateField("date de naissance", blank=True, null=True)
country = models.CharField("pays", max_length=64, blank=True)
And this is the admin.py of this class : 这是此类的admin.py:
class ProfilAdmin(admin.ModelAdmin):
list_display = ('user.username', 'user.email', 'country', 'user.is_staff')
list_filter = ('user.date_joined', 'user.is_staff')
search_fields = ('user.username', 'user.email', 'country', 'user.first_name')
admin.site.register(Profil, ProfilAdmin)
And of course, 'user.username'
doesn't work. 当然,
'user.username'
不起作用。 How can I get the username of my user through my Profil class? 如何通过Profil类获取用户的用户名?
This is the solution and it looks good : 这是解决方案,看起来不错:
class ProfilAdmin(admin.ModelAdmin):
list_display = ('get_username', 'get_email', 'country')
list_filter = ('get_date_joined', 'get_is_staff')
search_fields = ('user__username', 'user__date_joined', 'user__is_staff')
def get_username(self, obj):
return obj.user.username
get_username.short_description = 'User'
get_username.admin_order_field = 'user__username'
def get_email(self, obj):
return obj.user.email
get_email.short_description = 'Email'
get_email.admin_order_field = 'user__email'
def get_date_joined(self, obj):
return obj.user.date_joined
get_date_joined.short_description = 'Date joined'
get_date_joined.admin_order_field = 'user__date_joined'
def get_is_staff(self, obj):
return obj.user.is_staff
get_is_staff.short_description = 'Is staff'
get_is_staff.admin_order_field = 'user__is_staff'
But now I get the following error during the makemigrations : 但是现在在makemigrations期间出现以下错误:
SystemCheckError: System check identified some issues:
ERRORS:
<class 'accounts.admin.ProfilAdmin'>: (admin.E116) The value of 'list_filter[0]' refers to 'get_date_joined', which does not refer to a Field.
<class 'accounts.admin.ProfilAdmin'>: (admin.E116) The value of 'list_filter[1]' refers to 'get_is_staff', which does not refer to a Field.
I understand that is_staff
is a class method, but how can I access to it? 我知道
is_staff
是一个类方法,但是如何访问它呢?
You cannot reach the object directly. 您无法直接到达物体。 Instead you'll have to use a custom method.
相反,您必须使用自定义方法。 The following should get you started:
以下内容将帮助您入门:
class ProfilAdmin(admin.ModelAdmin):
list_display = ('get_username', )
search_fields = ['user__username', ]
def get_username(self, obj):
return obj.user.username
get_patient.short_description = 'User'
get_patient.admin_order_field = 'user__username'
See also Django admin list_display property usage . 另请参阅Django admin list_display属性用法 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.