1

Hello I need to delete some images of current logged in user from DB from html

here is my profile class

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image1 = models.ImageField(default=None, upload_to='images', blank=True)
    image2 = models.ImageField(default=None, upload_to='images', blank=True)
    image3 = models.ImageField(default=None, upload_to='images', blank=True)

thanks a lot

Arthur
  • 109
  • 8
  • `some_profile.image1.delete()`. Note that the images are *not* stored in the database, the path of the files is stored in the database. – Willem Van Onsem Aug 27 '19 at 09:16
  • @WillemVanOnsem but will that delete only current logged in user images? – Arthur Aug 27 '19 at 09:20
  • It will delete the image of the user `some_profile`. – Matthias Aug 27 '19 at 09:21
  • @Arthur: you can obtain the `Profile` of the logged in user with `request.user.profile`, so `request.user.profile.image1.delete()` – Willem Van Onsem Aug 27 '19 at 09:22
  • I need to implement an ability of current logged in user to be able to delete his/her images only. So I think I need to query images by current logged in user id... – Arthur Aug 27 '19 at 09:24
  • @Arthur: the profile of the current logged in user is `request.user.profile`, so then you can process that profile, for example by calling a `image1.delete()` on that profile. – Willem Van Onsem Aug 27 '19 at 09:26

1 Answers1

2

You can delete some reference to a file (with a FileField, or ImageField) with:

some_profile.image1.delete()

With some_profile the Profile object, and image1 the name of the field of the file you want to delete.

So in a view, you can delete this with:

def some_view(request):
    try:
        request.user.profile.image1.delete()
    except Profile.DoesNotExist:
        pass
    # ...

This will not remove the file itself from the media directory. There are several solutions to clean up media files.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555