我正在尝试模仿前端的Photologue应用程序的管理界面。为实现这一目标,我到目前为止在视图中创建了一些代码:
def galleryuploader(request):
GalleryFormSet = modelformset_factory(GalleryUpload)
if request.method == 'POST':
formset = GalleryFormSet(request.POST, request.FILES)
if formset.is_valid():
formset.save()
# do something. ... do what?
else:
formset = GalleryFormSet()
return render_to_response("cms_helper/gallery_upload.html", {
"formset": formset,
})
和模板:
<form method="post" action="">
{{ formset }}
<input type="submit" />
</form>
我正在使用django的“form from models”方法来生成此前端表单。
问题:当我尝试上传文件时(因为我将照片上传到照片库)并点击提交,它会返回一个表单错误,告诉我缺少必填字段(文件)。
我想我没有检查任何文件的请求,但即使我这样做,我也不太确定如何。这里有一些关于file uploads的文档,但我还没有解读它。
如果您对如何使此上传表单有任何建议,我会非常高兴听到它们。提前谢谢!
答案 0 :(得分:3)
将enctype="multipart/form-data"
属性添加到表单标记中。此外,您还需要对上传的文件执行某些操作。以下是django docs:
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
# you'll need to loop through the uploaded files here.
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
def handle_uploaded_file(f):
destination = open('some/file/name.txt', 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
(见中途评论)