所以我试图使用UserModel在我的模型中添加一个图像字段,所以我创建了这个模型
from django.contrib.auth.models import User
from django.db import models
class ProfileImage(models.Model):
user = models.OneToOneField(User,
on_delete=models.CASCADE,
editable=False)
avatar = models.ImageField()
def user_avatar(self):
return self.profileimage.avatar
User.add_to_class('user_avatar', user_avatar)
我让管理员查看了用户中的图像字段, admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
# Register your models here.
UserAdmin.fieldsets += ('Custom fields set', {'fields': ('user_avatar',)}),
答案 0 :(得分:1)
在管理员fields
和fieldsets
中,您希望列出数据库中的实际列。 user_avatar
是您编写的函数,因此无法在User
模型上将其列为字段,因为该表中不存在该函数。
为所有类型的用户信息(而不只是像这样的图像)建立更通用的模型;
class Profile(models.Model):
"""
Profile model
"""
user = models.OneToOneField(
verbose_name=_('User'),
to=settings.AUTH_USER_MODEL,
related_name='profile',
on_delete=models.CASCADE
)
avatar = models.ImageField()
然后,您可以使用request.user.profile.avatar
访问化身,或在管理员中将Profile
模型注册为User
的内联;
from django.contrib import admin
from django.contrib.auth import get_user_model
from myapp.accounts.models import Profile
User = get_user_model()
class ProfileInline(admin.StackedInline):
model = Profile
max_num = 1
can_delete = False
class MyUserAdmin(admin.UserAdmin):
inlines = [ProfileInline]
# unregister old user admin
admin.site.unregister(User)
# register new user admin that includes a UserProfile
admin.site.register(User, MyUserAdmin)