我有这个自定义类
class CustomUserAdmin(UserAdmin):
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'email', 'password1', 'password2', 'location')}
),
)
fieldsets = (
(None, {'fields': ('username', 'password')}),
(('Personal info'), {'fields': ('first_name', 'last_name', 'email', 'location')}),
(('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'user_permissions')}),
(('Important dates'), {'fields': ('last_login', 'date_joined')}),
(('Groups'), {'fields': ('groups',)}),
)
#UserAdmin.list_display += ('location',)
add_form = MyUserCreationForm
form = MyUserChangeForm
它工作正常,直到我取消注释这一行
UserAdmin.list_display + =('location',)
然后它给了我这个错误: CustomUserAdmin.list_display [5],'location'不是'CustomUserAdmin'的可调用或属性,或者在'User'模型中找到。
任何帮助?
[编辑]
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.OneToOneField(User)
location = models.CharField(max_length=30)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
答案 0 :(得分:2)
您不会修改UserAdmin吗?
假设location
是CustomUser
的实际字段,请尝试使用
list_display = UserAdmin.list_display + ('location',)
编辑:更简单的回答
使用标准的django方式在list_display
:
class CustomUserAdmin(UserAdmin):
# other things
def user_location(self, u):
try:
return u.get_profile().location
except:
return ''
user_location.short_description = 'Location'
list_display = UserAdmin.list_display + ('user_location',)
编辑:更多信息
无论如何,如果您只是为了添加配置文件字段而扩展UserForm,您应该查看此链接:http://www.thenestedfloat.com/articles/displaying-custom-user-profile-fields-in-djangos-admin/index.html以利用内联并避免从头开始重新创建整个表单。