Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django – Delete file associated with ImageField attribute of Model

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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)

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading