Home > Blockchain >  Django - Delete file associated with ImageField attribute of Model
Django - Delete file associated with ImageField attribute of Model

Time:01-12

So I have a model called User, which has an avatar field, which is just the user's avatar. I want to be able to delete the file whenever the user chooses to delete their avatar. As you can see below in my view.py I retrieve the current user object from the request(This is because I take the user uuid from the access token given to make the request then query the user object). Then I call delete on the avatar attribute, but I don't know if this actually deletes the file as well. My assumption is that it just deletes that attribute url. How do I delete the file associated with ImageField when I delete a ImageField attribute in a model?

model.py

class User(AbstractDatesModel):
    uuid = models.UUIDField(primary_key=True)
    username = models.CharField(max_length=USERNAME_MAX_LEN, unique=True, validators=[
        MinLengthValidator(USERNAME_MIN_LEN)])
    created = models.DateTimeField('Created at', auto_now_add=True)
    updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True)
    avatar = models.ImageField(upload_to=avatar_directory_path, blank=True, null=True)

view.py

@api_view(['POST', 'DELETE'])
def multi_method_user_avatar(request):
    if request.method == 'POST':
        # Some POST code
    elif request.method == 'DELETE':
        try:
            request.user.avatar.delete()
            request.user.save()

            return Response(status=status.HTTP_204_NO_CONTENT)
        except Exception as e:
            return Response(dict(error=str(e), user_message=generic_error_user_msg),
                            status=status.HTTP_400_BAD_REQUEST)

CodePudding user response:

Deleting an ImageField keeps the file on the system.

Change your code to this to delete the file:

#insert at top of file
import os

elif request.method == 'DELETE':
    try:
        os.remove(request.user.avatar.path)
        request.user.avatar.delete()
        request.user.save()
  •  Tags:  
  • Related