Django文件上传 [英] Django File Upload
问题描述
以下是视图中的代码:
def index(request):
if request.method == 'POST':
a = request.POST
#logging.debug(a [title])
#logging.debug(a [file])
#form = UploadFileForm()
form = UploadFileForm(request.POST,request.FILES)
#handle_uploaded_file(request.FILES ['file'])
如果form.is_valid():
handle_uploaded_file(request.FILES ['file'])
return HttpResponseRedirect('/')
else:
form = UploadFileForm()
return render('upload.html' ,{'form':form})
def handle_uploaded_file(file):
#logging.debug(upload_here)
如果文件:
destination = open('/ tmp /'+ file.name,'wb +')
#destination = open('/ tmp','wb +')
file.chunks()中的块:
destination.write(chunk)
destination.close()
以下是模型中的代码:
<$
title = forms.CharField(max_length = 50)
file = forms.FileField(type =file)
以下是upload.html中的代码:
{%block upload%}
< form enctype =multipart / form-datamethod =postaction =/ upload />
{%csrf_token%}
< table>
< tr>< td>
< input type =filevalue =titlename =titleid =title/>< br />
< input type =submitvalue =提交id =保存/>
< / td>< / tr>
< / table>
< / form>
{%endblock%}
选择文件后,按提交按钮,出现错误:
/ upload /
中的AttributeError'WSGIRequest'对象没有属性'chunks' / p>
请求方法:POST
请求URL: http:// www。 mywebsite.com/upload/
Django版本:1.3
异常类型:AttributeError
异常值:
'WSGIRequest 'object没有属性'chunks'
异常位置:handle_uploaded_file中的/usr/src/wpcms/views.py第63行
任何想法我在这里做错什么?我忘记了一个设置行吗?还是一条进口线?
谢谢。
settings.py是:
TEMPLATE_LOADERS =(
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES =(
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'cms.middleware.page.CurrentPageMiddleware',
'cms.middleware .user.currentUserMiddleware',
'cms.middleware.toolbar.ToolbarMiddleware',
'cms.middleware.media.PlaceholderMediaMiddleware',
'django.middleware.doc.XViewMiddleware',
'django_authopenid.middleware.OpenIDMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS =(
django.core.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.request' ,
'django.core.context_processors.media',
'cms.context_processors.media',
'django_authopenid.context_processors.authopenid',
)
CMS_TEMPLATES =(
#('basic.html','基本模板'),
#('template_1.html','模板1'),
#('template_2。 html','Template Two'),
('home.html',gettext('Default')),
('about.html',gettext('About')),
#('blog.html',gettext('blog')),
('contact.html',gettext('Contact')),
)
ROOT_URLCONF ='urls'
CMS_APPLICATIONS_URLS =(
('cmsplugin_news.urls','新闻'),
)
CMS_NAVIGATION_EXTENDERS =(
('cmsplugin_news.navigation.get_nodes ,'新闻导航'),
)
THUMBNAIL_PROCESSORS =(
'easy_thumbnails.processors.colorspace',
'easy_thumbnails.processors.autocrop',
#'easy_thumbnails.processors.scale_and_crop',
'filer.thumbnail_processors.scale_and_crop_with_subject_location',
'easy_thumbnails.processors.filters',
)
CMS_MODERATOR = False
TEMPLATE_DIRS =(
os.path.join(PROJECT_DIR,templates),
)
INSTALLED_APPS =(
'django .contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib ,
'django.contrib.admin',
'django.contrib.comments',
'registration',
'django_authopenid',
'cms ',
'menus',
'mptt',
'appmedia',
'south',
'cms.plugins.tex t',
'cms.plugins.picture',
'cms.plugins.link',
'cms.plugins.file',
'easy_thumbnails',
'filer',
'cmsplugin_filer_file',
'cmsplugin_filer_folder',
'cmsplugin_filer_image',
'cmsplugin_filer_teaser',
'cmsplugin_filer_video',
' cms.plugins.snippet',
'cms.plugins.googlemap',
'publisher',
'reversion',
'cms.plugins.teaser',
'cms.plugins.video',
'cms.plugins.twitter',
'cmsplugin_facebook',
'cmsplugin_news',
'cmsplugin_comments',
'
有多个的问题。这是一个固定的版本:
1)更改您的模板以使用实际的形式:
< form enctype =multipart / form-datamethod =postaction =/ upload />
{%csrf_token%}
< table>
{{form.as_table}}
< / table>
< input type =submitvalue =提交id =保存/>
< / form>
2)更新您的表单以删除FileField中不必要的类型:
class UploadFileForm(forms.Form):
title = forms.CharField(max_length = 50)
file = forms.FileField()
3)更新您的视图以添加CSRF:
pre $
def index(request):
if request.method =='POST':
a = request.POST
form = UploadFileForm(request。 POST,request.FILES)
如果form.is_valid():
handle_uploaded_file(request.FILES ['file'])
return HttpResponseRedirect('/')
else:
form = UploadFileForm()
c = {'form':form}
c.update(csrf(request))
return render_to_response('upload.html' c)
希望这有帮助!
Here is the code in views:
def index(request):
if request.method == 'POST':
a=request.POST
# logging.debug(a["title"])
# logging.debug(a["file"])
#form = UploadFileForm()
form = UploadFileForm(request.POST, request.FILES)
#handle_uploaded_file(request.FILES['file'])
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/')
else:
form = UploadFileForm()
return render('upload.html', {'form': form})
def handle_uploaded_file(file):
# logging.debug("upload_here")
if file:
destination = open('/tmp/'+file.name, 'wb+')
#destination = open('/tmp', 'wb+')
for chunk in file.chunks():
destination.write(chunk)
destination.close()
Here is the code in models:
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField(type="file")
Here is the code in upload.html:
{% block upload %}
<form enctype="multipart/form-data" method="post" action="/upload/">
{% csrf_token %}
<table>
<tr><td>
<input type="file" value="title" name="title" id="title" /><br />
<input type="submit" value="Submit" id="Save"/>
</td></tr>
</table>
</form>
{% endblock %}
After I select a file, then press the submit button, an error appears:
AttributeError at /upload/
'WSGIRequest' object has no attribute 'chunks'
Request Method: POST Request URL: http://www.mywebsite.com/upload/ Django Version: 1.3 Exception Type: AttributeError Exception Value:
'WSGIRequest' object has no attribute 'chunks'
Exception Location: /usr/src/wpcms/views.py in handle_uploaded_file, line 63
Any ideas what I am doing wrong here? Am I forgetting a settings line? Or, an import line? Thank you.
settings.py is:
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'cms.middleware.page.CurrentPageMiddleware',
'cms.middleware.user.CurrentUserMiddleware',
'cms.middleware.toolbar.ToolbarMiddleware',
'cms.middleware.media.PlaceholderMediaMiddleware',
'django.middleware.doc.XViewMiddleware',
'django_authopenid.middleware.OpenIDMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.request',
'django.core.context_processors.media',
'cms.context_processors.media',
'django_authopenid.context_processors.authopenid',
)
CMS_TEMPLATES = (
# ('basic.html', 'Basic Template'),
# ('template_1.html', 'Template One'),
# ('template_2.html', 'Template Two'),
('home.html', gettext('Default')),
('about.html', gettext('About')),
# ('blog.html', gettext('blog')),
('contact.html', gettext('Contact')),
)
ROOT_URLCONF = 'urls'
CMS_APPLICATIONS_URLS = (
('cmsplugin_news.urls', 'News'),
)
CMS_NAVIGATION_EXTENDERS = (
('cmsplugin_news.navigation.get_nodes', 'News navigation'),
)
THUMBNAIL_PROCESSORS = (
'easy_thumbnails.processors.colorspace',
'easy_thumbnails.processors.autocrop',
#'easy_thumbnails.processors.scale_and_crop',
'filer.thumbnail_processors.scale_and_crop_with_subject_location',
'easy_thumbnails.processors.filters',
)
CMS_MODERATOR = False
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'django.contrib.comments',
'registration',
'django_authopenid',
'cms',
'menus',
'mptt',
'appmedia',
'south',
'cms.plugins.text',
'cms.plugins.picture',
'cms.plugins.link',
'cms.plugins.file',
'easy_thumbnails',
'filer',
'cmsplugin_filer_file',
'cmsplugin_filer_folder',
'cmsplugin_filer_image',
'cmsplugin_filer_teaser',
'cmsplugin_filer_video',
'cms.plugins.snippet',
'cms.plugins.googlemap',
'publisher',
'reversion',
'cms.plugins.teaser',
'cms.plugins.video',
'cms.plugins.twitter',
'cmsplugin_facebook',
'cmsplugin_news',
'cmsplugin_comments',
'captcha',
)
There are multiple issues. Here is a fixed version that works:
1) Change your template to use the actual form:
<form enctype="multipart/form-data" method="post" action="/upload/">
{% csrf_token %}
<table>
{{form.as_table}}
</table>
<input type="submit" value="Submit" id="Save"/>
</form>
2) Update your form to remove unnecessary type in the FileField:
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
3) Update your view to add the CSRF:
def index(request):
if request.method == 'POST':
a=request.POST
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/')
else:
form = UploadFileForm()
c = {'form': form}
c.update(csrf(request))
return render_to_response('upload.html', c)
Hope this helps!
这篇关于Django文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!