简体   繁体   中英

How to upload a json.dump into a model FileField

I seem to not be able to work around this proble I have in my Django project

I have a model with a FileField. Now I'm trying to create a file of json data to store in this field. I've been working around this in different ways and I have come to the conclusion (right or wrong) that I shouldn't need to write a file, but be able to dump the data directly into the file.

All this is embedded in a custom_command.

My model

class Free_FileHistory(models.Model):
    free_file= models.FileField(upload_to=get_inv_file_filepath, null=True, blank=True, verbose_name='File',validators=[validate_file_size])

   ....

My code

   OBJ = Free_FileHistory.objects.get(free_transfer_id=ID) 
# ID is a unique identifier
   file = (ID)
# CreateDictioneryJSON is a my own function that take two given arrays of keys and values and create one data directory
   data = CreateDictioneryJSON(HEADER,ROW) 
   read=json.dumps(data, indent=4)
   print(read)
   OBJ.free_file.save(file,read)

print(read) displays the data just as I want it. I get the error: 'str' object has no attribute 'closed'

The solution was close. The code hade to be slightly modified

                file = (ID + '.json')
                OBJ = Free_FileHistory.objects.get(free_transfer_id=ID)
                data = CreateDictioneryJSON(HEADER,ROW)
                read=json.dumps(data, indent=4)
                txt= ContentFile(read.encode('utf-8'))
                OBJ.free_file.save(file, txt)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM