Django电子邮件附件问题

时间:2011-08-25 21:14:01

标签: django email attachment

我有一个表单模型:

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)

和观点:

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: {}>"错误。随着附件功能的取消,一切正常。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

attach = request.FILES['attach']替换为attach = request.FILES.get('attach'),以便当用户没有“附加”文件时,变量attach将为None

当你执行request.FILES['attach']时,你假设密钥存在,可能是由表单错误检查程序捕获的,但该字段不是required