Home > Net >  Django - How do you email a completed create view form
Django - How do you email a completed create view form

Time:12-29

I'm working on a property management app where users can fill out an online application for a property. I want to set it up so when someone fills out an application the form gets emailed to the admin formatted with the form labels. Is there a way to email an entire formatted form with labels or am I going to have to make an email template and tag it according to how I want it to look?

My example code:

class ApplicationView(CreateView):
    redirect_field_name = ''
    form_class = ApplicantForm
    model = Applicant
    template_name = 'base/application.html'

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        subject = 'New Application - {} {}'.format(
            form.cleaned_data.get('first_name'),
            form.cleaned_data.get('last_name'),
        )
        message = '{} {}'.format(
            form.cleaned_data.get('first_name'),
            form.cleaned_data.get('last_name'),
        )
        Application_Alert(subject, message)
        return super().form_valid(form)

CodePudding user response:

With emails, you have two options: a text based and a HTML based email. So, if you want a email formatted with labels and nicer looking format, you have to opt for HTML based option. As mentioned here.

The fastest approach is to create a templates/generic/_email.html and render it bypassing the context variable as you would in a ListView.

CodePudding user response:

We need 2 steps:

  • In your settings.py, add your email information:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'mail.example.com'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = '******'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
  • In your views.py, import your setting:
from django.conf import settings as my_settings
from django.core.mail import EmailMultiAlternatives

def your_def():
    subject = f"{request.user} send subject"
    from_email = my_settings.EMAIL_HOST_USER
    to_email = ['[email protected]', '[email protected]'...] 
    text_content = 'This is an important message.'
    # Add your email template here
    html_content = '<p>This is an <strong>important</strong> message.</p>'
    msg = EmailMultiAlternatives(subject, text_content, from_email, to_email)
    msg.attach_alternative(html_content, "text/html")
    msg.send()

You can see document at here.

  • Related