Closed saippuakauppias closed 4 years ago
Hi there, thanks for your suggestion. This is the current code to deal with FileFields.
django_file = data
if isinstance(django_file, File):
setattr(instance, field.name, data.name) # set the attribute
if django_file.file.mode != 'rb':
django_file.file.close() # this file may be open in another mode, for example, in a+b
opened_file = open(django_file.file.name, 'rb') # to save the file it must be open in rb mode
django_file.file = opened_file # we update the reference to the rb mode opened file
getattr(instance, field.name).save(django_file.name, django_file) # save the file into the file storage system
django_file.close()
else: # string (saving just a name in the file, without saving the file to the storage file system
setattr(instance, field.name, data) # Model.field = data
@paulocheque I've been working with files. Things work fine except that the above code tries to prematurely save the model instance while saving the image file to storage, causing IntegrityError:
It can be corrected by replacing:
getattr(instance, field.name).save(django_file.name, django_file) # save the file into the file storage system
django_file.close()
with
getattr(instance, field.name).save(django_file.name, django_file, save=False)
Notice the save=False
and removed django_file.close()
Cheers, and thanks for an awesome library!
The 1.9.0 version included your suggestion. Thanks!
Thanks @paulocheque! 😊
I'm writing custom fixture class for creating uploaded files. But this code must be in a package.