views:

67

answers:

3

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

A: 

I was trying this

file = open('mytest.pdf')
pdfImage.myfile.save('new', file)
file.close()

before, but I had this error:

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

A: 

See http://www.nitinh.com/2009/02/django-example-filefield-and-imagefield/. You need to pass save a Django request.

katrielalex
+2  A: 

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

file = open('mytest.pdf')
djangofile = File(file)
pdfImage.myfile.save('new', djangofile)
file.close()

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

pdfImage.myfile.save('new', File(file))`.
tux21b