我有一个表单模型:
class ManuscriptForm(forms.Form):
name = forms.CharField(label='Your Name')
sender = forms.EmailField(label='Your Email')
attach = forms.Field(label='Attach Your Manuscript', widget = forms.FileInput, required=False) # upload field!
subject = forms.CharField()
message = forms.CharField(widget = forms.Textarea)
cc_myself = forms.BooleanField(required=False)
和view:
def manuscript_form(request):
if request.method == 'POST': # If the form has been submitted...
form = ManuscriptForm(request.POST, request.FILES) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
name = form.cleaned_data['name']
sender = form.cleaned_data['sender']
attach = request.FILES['attach']
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
cc_myself = form.cleaned_data['cc_myself']
recipients = ['info@example.com']
if cc_myself:
recipients.append(sender)
from django.core.mail import send_mail, EmailMessage
mail = EmailMessage(subject, message, sender, recipients)
mail.attach(attach.name, attach.read(), attach.content_type)
mail.send()
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ManuscriptForm() # An unbound form
return render_to_response('manuscript_form.html', {
'form': form,
}, context_instance=RequestContext(request))
问题是我一直得到一个:"Key 'attach' not found in <MultiValueDict: {}>"
错误。去掉附件功能后,一切正常。有什么建议吗?
将attach = request.FILES['attach']
替换为attach = request.FILES.get('attach')
,这样当用户没有"附加"文件时,变量attach
将为None
。
当您执行request.FILES['attach']
时,您假设键存在,这可能已经被您的表单错误检查器捕获,除非字段不是required
。