Skip to main content
 首页 » 编程设计

python之将个人资料图片添加到 django 用户

2025年05月04日40lyj

我正在尝试关注 this发布以将个人资料图片与 Django 中的用户相关联。

我有以下模型

class MyUser(AbstractBaseUser): 
    """ 
    Custom user class. 
    """ 
 
    GENDER_CHOICES = ( 
        ('M', 'Male'), 
        ('F', 'Female'), 
    ) 
    email = models.EmailField('email address', unique=True, db_index=True) 
    is_staff = models.BooleanField('is staff', default=False) 
    first_name = models.TextField('first name', default=None, null=True) 
    last_name = models.TextField('last name', default=None, null=True) 
    date_of_birth = models.DateField('date of birth', null=True) 
    avatar = models.ImageField('profile picture', upload_to='static/media/images/avatars/', null=True, blank=True) 
    has_picture = models.BooleanField('has profile picture', default=False) 
    adult = models.BooleanField('is adult', default=False) 
    gender = models.CharField('gender', max_length=1, choices=GENDER_CHOICES) 
 
    objects = MyUserManager() 
 
    REQUIRED_FIELDS = ['date_of_birth', 'gender'] 
 
    USERNAME_FIELD = 'email' 
 
    # Insert a lot of methods here 
 
    def set_avatar(self): 
       self.has_picture = True 

我使用了帖子中的表单,但将其添加到我的更改表单的 save() 中:

def save(self, commit=True): 
    user = super(MyChangeForm, self).save(commit=False) 
    if user.avatar:          # If the form includes an avatar 
       user.set_avatar()     # Use this bool to check in templates 
    if commit: 
        user.save() 
    return user 

这背后的逻辑是添加一张图片然后设置一个 bool 标志来告诉模板是否显示一个通用的“空白用户”头像如果没有与配置文件关联的图片,如果有头像属性则显示缩略图用户。

在我的表单中,上传和 has_picture 字段都没有设置。但是,在管理员中,我可以上传照片。

我做错了什么?

请您参考如下方法:

设置一个 bool 值来检查用户是否有头像不是一个好主意。您有两个选择:您可以在模板中使用空 url 或在 models.py

中定义一个方法来设置用户头像

选项 1:在您的模板中

{% if user.avatar == None %} 
    <img src="DEFAULT_IMAGE" /> 
{% else %} 
    <img src="user.avatar"/> 
{% endif %} 

选项 2:在您的模型中

def set_avatar(self): 
    _avatar = self.avatar 
    if not _avatar: 
        self.avatar="path/to/default/avatar.png" 

此外,如果您的用户永远不会被保存,如果因为您使用 commit=False 调用保存方法。