Django : generate a file then save it in a FileField

I have a model Contract. When users create a new Contract, they only have to provide the name. Then, my code will generate a file, and save it in contract_file which is a FileField.

For this, I have a static method for generating the file, then I overwrite the save method of django's Model.

class Contract(models.Model):
    name = models.CharField(max_length=150, null=True)
    contract = models.FileField(upload_to = 'contrats/', blank=True, null=True)

    def save(self, *args, **kwargs):
        filename = self.generate_contract()
        f = open(filename, "r")
        self.contract.save(filename, f)
        return super(Refund, self).save(*args, **kwargs)

    @staticmethod
    def generate_contract():
        filename = settings.MEDIA_ROOT + 'test.txt'
        f = open(filename, "w")
        f.write("content")
        f.close()
        return filename

Unfortunately, this results in an

Exception Value: maximum recursion depth exceeded while calling a Python object

I suppose that when I call the FileField save method, it might somehow also call the Contract' save method. But I could not solve this problem. Does anyone have a method for performing this file generation then saving it ?

Upvotes: 2

Views: 2310

Answers (1)

Alex Ford
Alex Ford

Reputation: 659

When running self.contract.save(filename, f) add the save parameter through as shown below.

This will not run the Contract instance save method, which is causing your recursion.

self.contract.save(filename, f, save=False)

I would also recommend using with ... when opening files so they don't stay open. Shown below:

def save(self, *args, **kwargs):
    filename = self.generate_contract()
    with open(filename, "r") as f:
        self.contract.save(filename, f)
    return super().save(*args, **kwargs)

Upvotes: 4

Related Questions