سؤال

I have a generic create view that sends an email using data from my ModelForm if it's valid. The email should also have an attachment from the filefield on the form.

But I can't seem to figure out how to attach the file, and send the email. I'm currently getting a 'InMemoryUploadedFile' object has no attribute 'rfind' error.

My view:

from __future__ import absolute_import

from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView, CreateView
from django.core.urlresolvers import reverse, reverse_lazy
from django.http import HttpResponseRedirect
from django.core.mail import send_mail, send_mass_mail, EmailMessage

from .models import Job, Application
from .forms import ApplicationForm

class JobListView(ListView):
    model = Job

    def get_context_data(self, **kwargs):
        context = super(JobListView, self).get_context_data(**kwargs)
        context['jobs'] = self.is_expired=False
        return context

class JobDetailView(DetailView):
    model = Job

class ApplicationCreateView(CreateView):
    model = Application
    form_class = ApplicationForm
    success_url = 'submitted/'

    def dispatch(self, *args, **kwargs):
        self.job = get_object_or_404(Job, slug=kwargs['slug'])
        return super(ApplicationCreateView, self).dispatch(*args, **kwargs)

    def form_valid(self, form):
        #Get associated job and save
        self.object = form.save(commit=False)
        self.object.job = self.job
        self.object.save()

        # Gather cleaned data for email send
        first_name = form.cleaned_data.get('first_name')
        last_name = form.cleaned_data.get('last_name')
        email_address = form.cleaned_data.get('email_address')
        phone_number = form.cleaned_data.get('phone_number')
        salary_requirement = form.cleaned_data.get('salary_requirement')
        description = form.cleaned_data.get('description')
        portfolio_url = form.cleaned_data.get('portfolio_url')
        can_relocate = form.cleaned_data.get('can_relocate')
        start_date = form.cleaned_data.get('start_date')
        resume = form.cleaned_data.get('resume')

        #Compose message
        email = EmailMessage()
        email.body = 'Name:' + first_name + last_name + '\n' + 'Email:'  + email_address + '\n' + 'Phone number:' + str(phone_number) + '\n' + 'Salary requirement:' + str(salary_requirement) + '\n' + 'Description:' + description + '\n' + 'Portfolio:' + portfolio_url + '\n' + 'Can relocate:' + str(can_relocate) + '\n' + 'Start date:' + str(start_date)
        email.subject = 'A new application has been submitted'
        email.from_email = 'Job application <noreply@email.com>'
        email.to = ['email@email.com',]
        email.attach_file(resume)
        email.send()
        return HttpResponseRedirect(self.get_success_url())

    def get_context_data(self, *args, **kwargs):
        context_data = super(ApplicationCreateView, self).get_context_data(*args, **kwargs)
        context_data.update({'job': self.job})
        return context_data

My form:

from django.forms import ModelForm

from  .models import Application

class ApplicationForm(ModelForm):
    class Meta:
        model = Application
        fields = [
            'first_name',
            'last_name',
            'email_address',
            'phone_number',
            'salary_requirement',
            'resume',
            'portfolio_url',
            'description',
            'can_relocate',
            'start_date',
        ]
    def clean(self):
        cleaned_data = super(ApplicationForm, self).clean()
        resume = cleaned_data.get('resume')
        resume_ext = resume.name.lower().split('.')[1]
        if not resume_ext in ('pdf', 'doc', 'docx'):
            msg = u"Your file must be a PDF or DOC file type."
            self._errors["resume"] = self.error_class([msg])
            del cleaned_data["resume"]
        return cleaned_data

Thanks for the help!

هل كانت مفيدة؟

المحلول

Turns out I needed to take advantage of Django's EmailMessage class, as indicated in the docs: https://docs.djangoproject.com/en/1.6/topics/email/#emailmessage-objects

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top