如何在 Django 中用 None 保存 FileField?

2024-01-04

我有带有 Avatar 字段的模型配置文件,使用 FileField。

class Profile(models.Model):
    avatar = models.FileField(
        "Uploaded avatar of profile",
        storage=OverwriteStorage(),
        upload_to=avatar_photo_upload,
        null=True,
        blank=True,
    )

我编写了删除头像的函数,其中设置 avatar = None

def remove_avatar(self, request):
        profile = Profile.objects.get(user=request.user)
        profile.avatar = None
        profile.avatar.save()
        return Response({ 'status': 'ok', 'message': 'Avatar successfully removed' }, status=status.HTTP_200_OK)

在我的数据库中,头像存储为'', not null。为什么以及如何解决它?


改变你的模型

class Profile(models.Model):
    avatar = models.FileField(
        "Uploaded avatar of profile",
        storage=OverwriteStorage(),
        upload_to=avatar_photo_upload,
        null=True,
    )

去除blank option

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Django 中用 None 保存 FileField? 的相关文章

随机推荐