0
我有一個表格模式:Django的電子郵件附件問題
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 = ['[email protected]']
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: {}>"
錯誤。隨着附件功能取消,一切正常。有什麼建議麼?
你不需要做'request.FILES.get('attach',None)'?它不會拋出一個異常,只是'request.FILES.get('attach')' –
James Khoury:沒有'get'默認爲'None' –
@rm我試着用get,但現在拋出一個''NoneType'對象沒有屬性「name」錯誤。在我看來,'request.Files'沒有被傳遞''attach''的值,但我不知道爲什麼。 html輸出中肯定包含''.Not sure what try to now。 –