JasonTS
JasonTS

Reputation: 2589

How to check if FileField was uploaded?

I wanna store the "original" file name of an upload. This is because the file gets stored with a uuid as a new name. So I wrote this for my model:

 def save(self, *args, **kwargs):
         if self.file:
             self.original_filename = self.file.name
         super(MediaFile, self).save(*args,**kwargs)

However, it also stores the filename to self.original_filename when nothing new has been uploaded. Thus the original_filename becomes the uuid the second time i save this model (e.g updating some other field in the admin).

How to check in the save function if the FileField was really updated and a file has been uploaded? If possible I'd like to perform this check in the model so mit will work both for admin and custom upload pages.

Upvotes: 0

Views: 820

Answers (1)

yagus
yagus

Reputation: 1445

You can adjust the __init__ method to store the original file. This allows you to retrieve the original file in the save() method and compare it to the new file.

        __original_file = None

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.__original_file = self.file

        def save(self, *args, **kwargs):
            if self.file:
                if self.file != self.__original_file:
                    self.original_filename = self.file.name

            super(MediaFile, self).save(*args,**kwargs)
            self.__original_file = self.file

Upvotes: 2

Related Questions