How do I create an instance of a Django model with a FileField
?
For example, given a simple model
from django.db import models
class FileModel(models.Model):
model_file = models.FileField(upload_to='files')
How can I create an instance of FileModel
, passing in an existing file for the model_file
field?
You can open the existing file on the filesystem, wrap it in a Django File
instance, and pass that in to the field directly:
>>> from django.core.files import File
>>> from myproject.myapp.models import FileModel
>>> with open('/path/to/existing_file.txt') as f:
... wrapped_file = File(f)
... m = FileModel(model_file=wrapped_file)
... m.save()
...
>>> m.model_file.name
u'files/existing_file.txt'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With