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

Adding profile picture to django user

我正在尝试按照 this post 将个人资料图片与 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

我使用了 post 中的表单,但将其添加到我的 save() 中用于 ChangeForm:

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 标志来告诉模板是否显示通用 "blank user" 头像如果没有与个人资料关联的图片,如果有则显示缩略图用户内的头像属性。

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

我做错了什么?

设置一个布尔值来检查用户是否有头像不是个好主意。您有两个选择:您可以在模板中使用空 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 调用保存方法。