我正在尝试附上带有联系表单的文件。我的代码对于表单和视图看起来像这样:
if request.method == 'POST':
form = UploadCVForm(request.POST, request.FILES)
if form.is_valid(): # All validation rules pass
subject = "CV Sent from BiztechAfrica"
sender = form.cleaned_data['email']
message = "Some message goes in here"
name = form.cleaned_data['name']
recipients = ['herman@xxx.co.za']
cv_file = request.FILES['cv_file']
mail = EmailMessage(subject, message, sender, recipients)
mail.send()
return HttpResponse('Thanks') # Redirect after POST
else:
form = UploadCVForm()
这是我的forms.py:
class UploadCVForm(forms.Form):
subject = "CV Sent from BiztechAfrica"
name = forms.CharField(max_length=128)
email = forms.EmailField()
cv_file = forms.Field(label='CV', widget = forms.FileInput, required = True )
电子邮件工作正常,但我无法附加该文件,因为它一直给我一个表单错误,即文件上传输入字段不能为空,尽管我选择了要上传的文件。
有什么想法吗?我仍然是Django和Python的新手...
答案 0 :(得分:4)
我打赌你从表单模板中留下enctype="multipart/form-data"
的钱:
<form action="/wherever/" method="POST" enctype="multipart/form-data">
如果我每分钟都有一分钱,我就会花时间跟踪错误......