manually writing to model filefield in django views Oct
11
1
1

Django models.FileField is very helpful in simplifying file management, but sometimes you need to write/overwrite into a file field object in a view without having the admin helper functions available. It's not inherently clear how to do this manually. Never fear though it's still an easy process.

It's worth noting that Django uses a custom File class that acts as a wrapper around the python file object to add some enhanced functionality. You simply need to initialize a Django File with a python file to get a valid model.

Say you have something similar to the following model:

class FileExample(models.Model):
    test = models.FileField(upload_to='uploads')

You can then write something like this in your view:

from django.core.files import File
from test.models import FileExample

file_example = FileExample()

filename = '/path/to/file.txt'
f = open(filename, 'r')
djangofile = File(f)
file_example.test.save('filename.txt', djangofile)
f.close()

Furthermore you can combine some statements to simplify and shorten the process:

file_example = FileExample()
file_example.test.save('filename.txt', File(open('/path/to/file.txt', 'r')))
Bookmark and Share
blog comments powered by Disqus