开发者

Django email attachment issue

开发者 https://www.devze.com 2023-03-31 00:55 出处:网络
I have a form model: class ManuscriptForm(forms.Form): name = forms.CharField(label=\'Your Name\') sender = forms.EmailField(label=\'Your Email\')

I have a form model:

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)

and a 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))

The problem is I keep getting a:"Key 'attach' not found in <MultiValueDict: {}>" error. With attachment capability taken out, all works fine. Any suggestions?


replace the attach = request.FILES['attach'] with attach = request.FILES.get('attach') so that the variable attach will be None when no files are "attached" by the user.

When you do request.FILES['attach'] you're assuming that the key is present, which might have been caught by your form error checker, except that the field is not required.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号