Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a local file to the FileField in Django?

I was trying to assign a file from my disk to the FileField, but I have this error:

AttributeError: 'str' object has no attribute 'open'

My python code:

pdfImage = FileSaver() pdfImage.myfile.save('new', open('mytest.pdf').read()) 

and my models.py

class FileSaver(models.Model):      myfile = models.FileField(upload_to="files/")      class Meta:         managed=False 

Thank you in advance for your help

like image 536
Leodom Avatar asked Aug 17 '10 10:08

Leodom


People also ask

How do I save models in Django?

To create a file and save it to a model's FileField with Python Django, we can open the file with open . And then we can call save with the file. to open the file at the given path with open . Then we create File object with file handle f .

How do I view local files in Django?

Keep the file in django project root and add the following in the settings.py file. Then in the view do this. Update: In newer Django versions BASE_DIR is already defined in the settings.py file.


2 Answers

Django uses it's own file type (with a sightly enhanced functionality). Anyway Django's file type works like a decorator, so you can simply wrap it around existing file objects to meet the needs of the Django API.

from django.core.files import File  local_file = open('mytest.pdf') djangofile = File(local_file) pdfImage.myfile.save('new', djangofile) local_file.close() 

You can of course decorate the file on the fly by writing the following (one line less):

pdfImage.myfile.save('new', File(local_file)) 
like image 110
tux21b Avatar answered Sep 16 '22 19:09

tux21b


If you don't want to open the file, you can also move the file to the media folder and directly set myfile.name with the relative path to MEDIA_ROOT :

import os os.rename('mytest.pdf', '/media/files/mytest.pdf') pdfImage = FileSaver() pdfImage.myfile.name = '/files/mytest.pdf' pdfImage.save() 
like image 30
Lucas B Avatar answered Sep 16 '22 19:09

Lucas B