向UserAdmin添加额外字段
我有一个自定义的类
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)
1 个回答
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,这样可以利用内联功能,避免从头开始重新创建整个表单。