2016-07-19 4 views
0

저는 장고에 파일을 저장하고 업로드하는 데 문제가있었습니다. 나는이 튜토리얼을 읽고 실행하고있다. 나는이 붙어 있었어요 :파일이 업로드되지 않고 데이터베이스에 저장되지 않습니다

'tuple' does not support the buffer interface 

문제는 views.py에서 오는 것으로 보인다, 그것은 절약 사이 어딘가에 중지합니다. 나는 ... 당신이 올바른 방향으로 날 지점 수있는 희망

내 업로드 forms.py/views.py

# -*- coding: utf-8 -*- 
from django.shortcuts import render_to_response 
from django.template import RequestContext 
from django.http import HttpResponseRedirect 
from django.core.urlresolvers import reverse 

from upload.models import Files 
from upload.forms import DocumentForm 

# import sys, traceback 

def index(request): 
    # Handle file upload 
    if request.method == 'POST': 
     form = DocumentForm(request.POST, request.FILES) 
     if form.is_valid(): 
      newdoc = Files(file_path = request.FILES['file_path']) 
      newdoc.save() 
      # print(request) 

     # Redirect to the document list after POST 
     return HttpResponseRedirect(reverse('upload.views.index')) 
    else: 
     form = DocumentForm() # A empty, unbound form 

    # Load documents for the list page 
    documents = Files.objects.all() 

    # print(form) 
    print(documents) 
    # Render list page with the documents and the form 
    return render_to_response(
     'upload/index.html', {'documents': documents, 'form': form}, RequestContext(request) 
) 

내 업로드/models.py

from django.db import models 

# Create your models here. 
class Files(models.Model): 
    user_id = models.IntegerField() 
    project_id = models.IntegerField() 
    file_path = models.FileField(upload_to='documents/%Y/%m/%d') 
    file_name = models.CharField(max_length=255) 
    file_size = models.CharField(max_length=45) 
    file_type = models.CharField(max_length=45) 
    file_ext = models.CharField(max_length=10) 
    file_width = models.SmallIntegerField() 
    file_height = models.SmallIntegerField() 
    file_tag = models.CharField(max_length=45) 
    location = models.TextField() 
    approved = models.IntegerField() 
    archived = models.IntegerField() 
    restored = models.IntegerField() 
    backup = models.IntegerField() 
    date_upload = models.DateTimeField() 
    date_modified = models.DateTimeField() 

    def __str__(self): 
     return 'file_name:{0}'.format(self.file_name) 

    class Meta: 
     managed = False 
     db_table = 'files' 

업로드/

Environment: 


Request Method: POST 
Request URL: http://localhost:8000/upload/ 

Django Version: 1.9 
Python Version: 3.4.3 
Installed Applications: 
['django.contrib.admin', 
'django.contrib.auth', 
'django.contrib.contenttypes', 
'django.contrib.sessions', 
'django.contrib.messages', 
'django.contrib.staticfiles', 
'gallery', 
'upload'] 
Installed Middleware: 
['django.middleware.security.SecurityMiddleware', 
'django.contrib.sessions.middleware.SessionMiddleware', 
'django.middleware.common.CommonMiddleware', 
'django.middleware.csrf.CsrfViewMiddleware', 
'django.contrib.auth.middleware.AuthenticationMiddleware', 
'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 
'django.contrib.messages.middleware.MessageMiddleware', 
'django.middleware.clickjacking.XFrameOptionsMiddleware'] 



Traceback: 

File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\core\handlers\base.py" in get_response 
    149.      response = self.process_exception_by_middleware(e, request) 

File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\core\handlers\base.py" in get_response 
    147.      response = wrapped_callback(request, *callback_args, **callback_kwargs) 

File "G:\python\testify\upload\views.py" in index 
    18.    newdoc.save() 

File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\base.py" in save 
    697.      force_update=force_update, update_fields=update_fields) 

File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\base.py" in save_base 
    725.    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) 

File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\base.py" in _save_table 
    809.    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) 

File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\base.py" in _do_insert 
    848.        using=using, raw=raw) 

File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\manager.py" in manager_method 
    122.     return getattr(self.get_queryset(), name)(*args, **kwargs) 

File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\query.py" in _insert 
    1037.   return query.get_compiler(using=using).execute_sql(return_id) 

File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\sql\compiler.py" in execute_sql 
    985.    for sql, params in self.as_sql(): 

File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\sql\compiler.py" in as_sql 
    943.     for obj in self.query.objs 

File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\sql\compiler.py" in <listcomp> 
    943.     for obj in self.query.objs 

File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\sql\compiler.py" in <listcomp> 
    941.     ) for f in fields 

File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\fields\files.py" in pre_save 
    311.    file.save(file.name, file, save=False) 

File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\fields\files.py" in save 
    90.   name = self.field.generate_filename(self.instance, name) 

File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\fields\files.py" in generate_filename 
    332.   return os.path.join(self.get_directory_name(), self.get_filename(filename)) 

File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\fields\files.py" in get_filename 
    322.   return os.path.normpath(self.storage.get_valid_name(os.path.basename(filename))) 

File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\utils\functional.py" in inner 
    205.    self._setup() 

File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\core\files\storage.py" in _setup 
    333.   self._wrapped = get_storage_class()() 

File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\core\files\storage.py" in __init__ 
    185.   self.location = abspathu(self.base_location) 

File "c:\python\lib\ntpath.py" in abspath 
    547.     path = _getfullpathname(path) 

Exception Type: TypeError at /upload/ 
Exception Value: 'tuple' does not support the buffer interface 
  • 업데이트 : 그것은 이제 데이터베이스에 저장 , 난 그냥 newdoc에서 모든 필드를 추가했습니다.

    file_path = request.FILES['file_path'] 
    
+0

전체 추적? –

+0

'request.FILES [ 'file_path'] 대신에'.read()'를 사용하여 파일 스팀 객체를 사용해야합니다. – MaNKuR

+0

양식'DocumentForm'도 게시하십시오. –

답변

3

FileField는 업로드 된 파일 개체를 나타냅니다에서 내 테이블에 NULL 값을 허용하지 않는 문제가 있지만입니다. 따라서 파일이 아니라 경로이 아닌 파일을 전달해야합니다.

def index(request): 
    # Handle file upload 
    if request.method == 'POST': 
     form = DocumentForm(request.POST, request.FILES) 
     if form.is_valid(): 
      newdoc = Files(file_path = form.cleaned_data['file_path']) 
      newdoc.save() 
      # print(request) 

documentation on file uploads은 이것에 대해 자세히 설명합니다.

+0

안녕하세요, file_path를 파일로 변경했지만 여전히 MultiValueDictKeyError 오류를 반환합니다. – mmr

0

나는 이미 내 문제를 해결했다고 생각하며,이 솔루션을 게시 할 때이 작업을하려는 다른 초보자가있을 경우에 대비해 생각합니다. 참고 : 파일 필드의 이름을 'File_path'에서 내 DocumentForm에있는 'file'로 바꾸면 이름 혼란을 피할 수 있습니다.

def index(request): 
    # Handle file upload 
    if request.method == 'POST': 
     form = DocumentForm(request.POST, request.FILES) 

     if form.is_valid(): 
      # Upload the File 
      uploaded_file(request) 
      # Save in database 
      newdoc = Files(
       file_path = 'media/'+request.FILES['file_path'].name, 
       file_name = request.FILES['file_path'].name, 
       file_size = request.FILES['file_path'].size, 
       file_type = request.FILES['file_path'].content_type, 
       # Other data fields here.. 
      ) 
      newdoc.save() 

     # Redirect to the document list after POST 
     return HttpResponseRedirect(reverse('upload.views.index')) 
    else: 
     form = DocumentForm() # A empty, unbound form 

    # Load documents for the list page 
    documents = Files.objects.all() 

    # Render list page with the documents and the form 
    return render_to_response(
     'upload/index.html', {'documents': documents, 'form': form}, RequestContext(request) 
    ) 

def uploaded_file(request): 
    uploaded_filename = request.FILES['file_path'].name 

    # save the uploaded file inside that folder. 
    full_filename = 'media/'+uploaded_filename 
    fout = open(full_filename, 'wb+') 

    file_content = ContentFile(request.FILES['file_path'].read()) 

    # Iterate through the chunks. 
    for chunk in file_content.chunks(): 
     fout.write(chunk) 
    fout.close() 
관련 문제