How to save FileField with None in Django?

Viewed 1551

I have model Profile with Avatar field use FileField.

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

I write function to remove avatar, which set 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)

In my database, avatar stored as '', not null. Why and how can I fix it?

1 Answers

change your model

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

remove the blank option

Related