简体   繁体   中英

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.

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.

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.

The problem is: When the user updates object's attributes other than the ImageField attribute, the signal still deletes the locally saved image file..

How can I change the signal to delete the file only if a new file was selected in django admin?

In other words, I need to check if the user uploaded a file while trying to update the object in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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