Search code examples
djangodjango-formsdjango-file-upload

Django Fileupload With Email


I am trying to attach a file with a contact form. My code looks like this for the form and view:

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()

This is my 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 )

The email works fine, but I cant attach the file because it keeps giving me a form error that the file upload input field can't be empty although I have selected a file to upload.

Any ideas? I am still a newb to Django and Python...


Solution

  • I'd bet money you left off enctype="multipart/form-data" from your form template:

    <form action="/wherever/" method="POST" enctype="multipart/form-data">
    

    If I had a penny for every minute I've spent trying to track errors like that down...