Skip to content
Advertisement

Django – how to create a file and save it to a model’s FileField?

Here’s my model. What I want to do is generate a new file and overwrite the existing one whenever a model instance is saved:

JavaScript

I see lots of documentation about how to upload a file. But how do I generate a file, assign it to a model field and have Django store it in the right place?

Advertisement

Answer

You want to have a look at FileField and FieldFile in the Django docs, and especially FieldFile.save().

Basically, a field declared as a FileField, when accessed, gives you an instance of class FieldFile, which gives you several methods to interact with the underlying file. So, what you need to do is:

JavaScript

where new_name is the filename you wish assigned and new_contents is the content of the file. Note that new_contents must be an instance of either django.core.files.File or django.core.files.base.ContentFile (see given links to manual for the details).

The two choices boil down to:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement