简体   繁体   English

Django - 删除与 Model 的 ImageField 属性关联的文件

[英]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.所以我有一个名为User的 model ,它有一个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).正如您在下面的view.py中看到的那样,我从request中检索当前用户 object(这是因为我从发出请求的访问令牌中获取用户 uuid,然后查询用户对象)。 Then I call delete on the avatar attribute, but I don't know if this actually deletes the file as well.然后我在avatar属性上调用delete ,但我不知道这是否真的也删除了文件。 My assumption is that it just deletes that attribute url .我的假设是它只是删除了该属性url How do I delete the file associated with ImageField when I delete a ImageField attribute in a model?删除 model 中的 ImageField 属性时,如何删除与 ImageField 关联的文件?

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)

Deleting an ImageField keeps the file on the system.删除 ImageField 会将文件保留在系统上。

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

request.user.avatar.delete() is sufficient. request.user.avatar.delete()就足够了。 I ran a test that checks if the file is removed 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.使用os.remove在已部署的服务器上不起作用,因为您无权访问该级别的文件系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM