1

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)
  • Does this answer your question? [Django delete FileField](https://stackoverflow.com/questions/16041232/django-delete-filefield) – lanhao945 Jan 11 '22 at 07:04
  • @HaoLan yea I would say so, but the person below gave a quicker more direct answer. –  Jan 11 '22 at 14:10
  • I just want to tell you ,try searching a question before putting a question. – lanhao945 Jan 11 '22 at 14:42
  • And do `os.remove` is not a good method,if you use other filesystem,not local filesystem,such object storage. – lanhao945 Jan 11 '22 at 14:43
  • @HaoLan I did search. I just wasn't sure if there were different intricacies between ImageFileField and FileField. For example, perhaps ImageFileField has built in functionality to remove files. –  Jan 11 '22 at 15:27
  • @HaoLan they're also using `os.remove` in the post you suggested as an answer as well. What should be used instead? –  Jan 11 '22 at 15:27
  • just `avatar.delete()`. You may have a read about the storage api about django:https://docs.djangoproject.com/en/4.0/ref/files/storage/. – lanhao945 Jan 12 '22 at 00:49
  • @HaoLan are you saying avatar.delete() is enough? –  Jan 12 '22 at 10:40
  • In my option,Yes.You can have a try. – lanhao945 Jan 12 '22 at 12:50
  • actually I don't think `os.remove` works because if you're connected to an Amazon S3 server you don't have OS access. –  Jan 12 '22 at 22:34
  • Yeah,try to use `delete` – lanhao945 Jan 13 '22 at 00:43

2 Answers2

0

request.user.avatar.delete() is sufficient. I ran a test that checks if the file exists prior to calling that end point and is deleted post calling the endpoint and it passes. Using os.remove doesn't work on deployed server because you don't have access to their file system at that level.

-1

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()
Josh Ackland
  • 603
  • 4
  • 19