2010-08-17 2 views
21

내가 FileField와 내 디스크에서 파일을 할당하려고했지만, 나는이 오류가 :Django의 FileField에 로컬 파일을 할당하는 방법은 무엇입니까?

AttributeError를 :

pdfImage = FileSaver() 
pdfImage.myfile.save('new', open('mytest.pdf').read()) 
: 'STR'개체가 어떤 속성 '열'

내 파이썬 코드가 없습니다

내 models.py

class FileSaver(models.Model): 

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

    class Meta: 
     managed=False 

당신의 도움에 미리 감사

답변

32

장고는 자신의 file type을 사용합니다 (눈에 띄게 기능이 향상되었습니다). 어쨌든 Django의 파일 유형은 decorator처럼 작동하므로 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() 

당신은 물론 (이하 한 줄) 다음를 작성하여 즉석에서 파일을 장식 할 수 있습니다

pdfImage.myfile.save('new', File(local_file))`. 
+3

아마 나쁜 생각 덮어 쓰기. 파일 사용을 더 잘함 _ –

+7

위의 설명을 설명하기 위해 (나는 약간 혼란 스러웠다.) Aaron은 전달 된 인수의 유형보다는 '파일'(즉, 변수의 이름) 기호에 대해 이야기하고있다. – Joe

관련 문제