0
class ModelFile(models.Model):
    ufile = models.FileField(upload_to="files")

And I have some management command and inside:

...
my_file = ModelFile.objects.create(ufile='/home/myfile.txt')

And I have objects instance, but I don't see myfile.txt in my files directory in project? What am I doing wrong?

bignose
  • 30,281
  • 14
  • 77
  • 110
Jeroj82
  • 401
  • 3
  • 14

3 Answers3

0

The reason is that creating a new modelfile with just a file path doesn't actually duplicate the file - it just links to the one that already exists. To actually duplicate the file you can use ContenFile like in the SO answer here: Duplicate Model Instance

Community
  • 1
  • 1
Hybrid
  • 6,741
  • 3
  • 25
  • 45
0

And I have [the model] instance, but I don't see myfile.txt in my files directory in project?

That's right. Model.create creates an instance of the model, with all the field values you specified.

There is nothing in your code that would create a corresponding file on the filesystem.

bignose
  • 30,281
  • 14
  • 77
  • 110
0
from django.core.files import File

instance = ModelFile.objects.create()
with open('/home/filename.txt', 'w') as file:
    instance.ufile.save('filename.txt', File(file))
Evgeni Shudzel
  • 231
  • 2
  • 5