Home > other >  How to read a file from storage and save as a model.FileField object?
How to read a file from storage and save as a model.FileField object?

Time:10-12

I have a model.FileField:

class MyModel(models.Model):
    myfile = models.FileField()

I have a default file on my storage that I want to set as a default post instance creation, so I am attempting to do this with a post_save signal:

@receiver(post_save, sender=MyModel)
def post_save_mymodel_setup(sender, instance, created, **kwargs):

    if instance and created:
        with open('/path/to/default_file.pdf', 'r') as f:
            fileobj = File(f, name='default_file.pdf')

            obj = MyModel(myfile=fileobj)
            obj.save()

However, this results in I/O operation on closed file.. Where am I going wrong?

CodePudding user response:

You create a new instance of a MyModel in your signal instead of filling the field. So whey instance is saving the is triggered, creates another instance, which triggers another signal, which creates another instance, and so on. You can do like this:

@receiver(post_save, sender=MyModel)
def post_save_mymodel_setup(sender, instance, created, **kwargs):

    if instance and created:
        with open('asd.py', 'r') as f:
            fileobj = File(f, name='default_file.pdf')

            instance.myfile = fileobj
            instance.save()

But the best practice is to fill this field with the overridden MyModel.save() method.

  • Related