Home > Back-end >  Use Django models.FileField to read file from memory and discard it before it is written to the dire
Use Django models.FileField to read file from memory and discard it before it is written to the dire

Time:10-07

How can I read a file using Django's models.FileField, handle the data in memory, and then discard it before django tries to save/write it to my directory. I want to discard the file, but still save the other fields for the model. I now that I can use forms and views to handle files, but I want to do it through the admin interface without a lot of extra logic

class DataField(models.Model):
    file = models.FileField()
    title = models.CharField()

    def save(self, *args, **kwargs):
        super(DataField, self).save(*args, **kwargs)

        some_background_task(self.file)
        # skip saving the file and avoid writing to directory, but save other fields

CodePudding user response:

class DataField(models.Model):
    file = models.FileField(null=True)
    title = models.CharField()

    def save(self, *args, **kwargs):
        some_background_task(self.file)
        self.file = None

        super(DataField, self).save(*args, **kwargs)
  • Related