在 Django Rest Framework 中更新 ImageField 并删除旧图像的最简单方法是什么?

What is the easiest way to UPDATE ImageField in Django Rest Framework and delete old image?

我想更新我的图像字段并使用 Django-rest 框架删除旧的。

这是我的模型

class GroupPostsModel(models.Model):
post_text = models.CharField(max_length=1000)
post_type = models.CharField(max_length=20)
image = models.ImageField(blank=True, null=True, upload_to='post_images/')
document = models.FileField(blank=True,null=True, upload_to='post_documents/')
likes = models.IntegerField(default=0)
time_stamp = models.DateTimeField(auto_now=True)
group = models.ForeignKey(GroupsModel, on_delete=models.CASCADE)
user = models.ForeignKey(UserModel, on_delete=models.CASCADE)

class Meta:
    db_table = 'group_posts'

我的views.py如下

@api_view(['PATCH'])
def save_edited_post_image(request):
image = request.data.get('image')
print('image == ')
print(request.data.get('image'))
post_id = request.data.get('post_id')
print('post id = '+str(post_id))
try:
    GroupPostsModel.objects.filter(id=post_id).update(image=image)
    resp = {
        'resp' : 'Post image updated...!'
    }
except Exception as e:
    print(e)
    resp = {
        'resp': 'Error: Post image update failed...!'
    }
return Response(resp)

代码没有抛出错误,但没有按预期工作。在数据库中,它将值存储为 image_name.jpeg;

要存储的预期值:post_images/1640341471608.jpeg

您必须创建一个方法,在上传后和保存前重命名文件,有很多教程对此进行了演示。

在views.py

@api_view(['POST'])

def save_edited_post_image(request):
image = request.data.get('image')
print('image == ')
print(request.data.get('image'))
post_id = request.data.get('post_id')
print('post id = '+str(post_id))
im = request.FILES['image']
print(im)
try:
    post = GroupPostsModel.objects.get(id=post_id)
    try:
        os.remove(post.image.path)
        print('Old post image deleted...! path = '+str(post.image.path))
    except Exception as e:
        print('No image for delete '+str(e))

    post.image = request.FILES['image'] #Worked..
    
    post.save()
    resp = {
        'resp' : 'Post image updated...!'
    }
except Exception as e:
    print(e)
    resp = {
        'resp': 'Error: Post image update failed...!'
    }
return Response(resp)