Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an instance of a Django model with a FileField

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?

like image 687
gotgenes Avatar asked Oct 15 '25 10:10

gotgenes


1 Answers

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'
like image 152
gotgenes Avatar answered Oct 17 '25 17:10

gotgenes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!