我有一个文件上传表单,我无法成功验证。 表单加载正常,我可以上传文件,但在提交后#39;我无法通过视图中的Fileform.is_valid()。我主要从Django 1.9 File Uploads文档中复制了这个视图以及模型和表单模型,但我必须遗漏一些东西。
view.py是,
def file_sharing_form(request):
if request.method == "POST":
file = FileForm(request.POST, request.FILES)
if file.is_valid():
fform = file.save(commit=False)
fform.author = request.user
fform.pub_date = timezone.now()
fform.submitted_date = timezone.now()
fform.approved = False
fform.save()
# email admin
admin_email = User.objects.all().filter(is_superuser = True)
subject = 'File submitted to QQIresources, awaiting approval'
to_email = admin_email[0].email
from_email = request.user.email
message = 'A file has been submitted to QQIresources by ' + str(request.user) + ' and is awaiting admin approval. \n \n Title: ' + str(fform.title) + '\n Author: ' + str(fform.author) + '\n Description: ' + str(fform.description)
send_mail(subject, message, from_email, [to_email])
return redirect('init')
fileform = FileForm()
return render(request, 'file_form.html', {'fileform': fileform})
答案 0 :(得分:2)
我猜你错过了enctype =" multipart / form-data"在你的HTML中。请在表单定义中为任何类型的文件上传添加此内容。
<form action="{% url 'your_url' %}" enctype="multipart/form-data">
<input type="file">
</form>