我正在尝试为我的新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)
这是这个类的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)
当然,'user.username'
并不起作用。如何通过Profil课程获取用户的用户名?
这是解决方案,看起来不错:
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'
但现在我在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.
我理解is_staff
是一种类方法,但我该如何访问它?
答案 0 :(得分:1)
您无法直接联系到该对象。相反,你必须使用自定义方法。以下内容可以帮助您入门:
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'