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()'new', open('mytest.pdf').read())

and my

class FileSaver(models.Model):

    myfile = models.FileField(upload_to="files/")

    class Meta:

Thank you in advance for your help

8/17/2010 10:48:36 AM

Accepted Answer

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)'new', djangofile)

You can of course decorate the file on the fly by writing the following (one line less):'new', File(local_file))
2/4/2019 9:41:11 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow