2017-09-15 1 views
0

파이썬에서 파일을 생성하고 해당 파일을 django 데이터베이스에 업로드하려고합니다. 이렇게하면 자동으로 미디어 폴더에 저장되고 내 응용 프로그램의 다른 모든 파일과 함께 정리됩니다. (이것은 파이썬 3.6 이후 유형 힌트가 사용)"Upload"파일을 Django에서 디스크

# forms.py 
class UploadForm(forms.ModelForm): 
    class Meta: 
     model = UploadedFile 
     fields = ('document',) 

# models.py 
class UploadedFile(models.Model): 
    document = models.FileField(upload_to=get_upload_path) 

    # mimetype is generated by filename on save 
    mimetype = models.CharField(max_length=255) 

    # ... additional fields like temporary 

def get_upload_path(instance: UploadedFile, filename): 
    if instance.temporary: 
     return "uploaded_files/temp/" + filename 
    return "uploaded_files/" + filename 

# views.py, file_out has been generated 
with open(file_out, 'rb') as local_file: 
    from django.core.files import File 
    form = UploadForm(dict(), {'document': File(local_file)}) 
    print(form.errors) 
    if form.is_valid(): 
     file = form.save(commit=False) 
     # ... set additional fields 
     file.save() 
     form.save_m2m() 
     return file 

지금이 내가 해봤 유일한 것이 아니다 : 지금 여기

내가 뭘하려합니다. 먼저 FileField을 직접 설정했으나 save()이 실패하고 mimetype 필드가 설정되었습니다. 원본 파일이 미디어 폴더 외부에 있기 때문에 의심스러운 파일 작업이 트리거됩니다.

또한 양식은 form.errors을 통해 "업로드"에 대한 피드백을 제공합니다.

내 접근 방식에 따라 save()은 위에서 언급 한 것처럼 실패합니다. 즉, "업로드"가 실제로 미디어 폴더에 파일을 복사하지 않는다는 의미입니다. 또는 양식이 파일이 전송되지 않았다는 오류를 반환하고 알려줍니다. 양식 프로토콜을 확인하십시오.

내 이론은 내가 가서 InMemoryUploadedFile의 고유 한 인스턴스를 초기화해야한다는 것입니다.하지만 그 방법을 직접 알 수는 없으며 인터넷에서 사용할 수있는 설명서가 없습니다.

나는 가야 할 때가 잘못된 접근 방식을 취하고있는 것처럼 느껴집니다. 어떻게하면 제대로 할 수 있습니까?

답변

0

첫째, Franey 덕분에 저를 contentfile documentation로 안내하는 storage documentation으로 안내해주었습니다.

ContentFile은 기본적으로 내가 찾고있는 InMemoryUploadedFile의 자체 인스턴스화 버전이므로 실제로 문제를 해결합니다. 디스크에 저장되지 않은 장바구니 File입니다.

# views.py, file_out has been generated 
with open(file_out, 'rb') as local_file: 
    from django.core.files.base import ContentFile 

    # we need to provide a name. Otherwise the Storage.save 
    # method reveives a None-parameter and breaks. 
    form = UploadForm(dict(), {'document': ContentFile(local_file.read(), name=name)}) 
    if form.is_valid(): 
     file = form.save(commit=False) 
     # ... set additional fields 
     file.save() 
     form.save_m2m() 
     return file 
1

get_upload_path이 정의되어 있습니까? 그렇지 않다면, 당신이 받고있는 오류를 설명 할 것입니다.

내가 옳은 길을 걷고있는 것을 볼 수 있습니다. 당신이 media/uploads 당신이 단지 그들을 원하는 경우, 업로드를위한 동적 경로를 필요로하지 않는 경우합니다 (Django docs에서) upload_to에 대한 문자열 값에 전달할 수 있습니다 모든

# file will be uploaded to MEDIA_ROOT/uploads 
document = models.FileField(upload_to='uploads/') 
+0

내가 확실히 수행

여기에 전체 솔루션입니다. 이 모델은 정규 파일 업로드에서'document'를 얻을 때 잘 동작합니다. –

+0

제 질문에이 기능을 추가했습니다. 편집을 참조하십시오. –

+0

그렇지 않으면 알 수없는가요? 곧 현상금을 추가 할 것입니다. –

관련 문제