简体   繁体   English

如何使用pre_save信号检查django admin中是否选择了新文件?

[英]How to check if a new file was selected in django admin using a pre_save signal?

I have a model that has an ImageField attribute. 我有一个具有ImageField属性的模型。

I update the model objects using the django admin and I needed something to delete the old image when a new image is uploaded while trying to update an object. 我使用django管理员更新了模型对象,并且在尝试更新对象时上传新图像时,我需要一些删除旧图像的方法。

So I created a pre_save signal that should delete the old image file from the server when the user attempts to update the model object. 因此,我创建了一个pre_save信号,当用户尝试更新模型对象时,该信号应从服务器上删除旧的图像文件。

The problem is: When the user updates object's attributes other than the ImageField attribute, the signal still deletes the locally saved image file.. 问题是:当用户更新除ImageField属性以外的对象的属性时,信号仍将删除本地保存的图像文件。

How can I change the signal to delete the file only if a new file was selected in django admin? 仅在django admin中选择了新文件时,如何更改信号以删除文件?

In other words, I need to check if the user uploaded a file while trying to update the object in django admin. 换句话说,我需要在尝试在django admin中更新对象时检查用户是否上传了文件。

IMPORTANT NOTE: My signal works with many models.. and I need to keep it like that. 重要说明:我的信号适用于许多型号。.我需要保持这种状态。

Here is the signal code: 这是信号代码:

@receiver(pre_save)
def pre_save_image_delete(sender, instance, **kwargs):
    if not valid_model(sender.__name__):
        return

    # Get file path on the server
    path = get_photo_path(sender.__name__, instance.pk)

    # delete the file if it exists
    if path and file_exists(path):
        delete_file(path)

Here is the solution after trying many things: 经过许多尝试后,这是解决方案:

if str(photo.path) == str(photo.file):
    return

The above code will be true only if there was no new file uploaded during object update. 上面的代码只有在对象更新过程中没有上传新文件的情况下才是正确的。

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

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