2

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?

djvg
  • 11,722
  • 5
  • 72
  • 103
KitKit
  • 8,549
  • 12
  • 56
  • 82

1 Answers1

3

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

djvg
  • 11,722
  • 5
  • 72
  • 103
Exprator
  • 26,992
  • 6
  • 47
  • 59
  • 1
    Did this ever work? At least it does not work in Django 3.2. Try and see: `Profile.objects.create(avatar=None).avatar is not None` Instead, you still get a ``. – djvg Jun 02 '22 at 13:09
  • @djvg no, it didn't and still does not. The one way I found is to override `django.db.models.fields.files.FileField.get_prep_value` method and use my own model fields. Django even has a 14 years old ticket for this https://code.djangoproject.com/ticket/10244 =) – Seg-mel Dec 27 '22 at 14:18