0

can't figure out how to call send_email in the forms.py from views.py can anybody please help me. it's a scoping issue

forms.py

from django import forms
from django.core.mail import send_mail


class ContactForm(forms.Form):
    subject = forms.CharField(max_length=75)
    message = forms.CharField(widget=forms.Textarea)
    sender = forms.EmailField()

    def send_email(self):
        send_mail(subject, message, sender, 'TheAndrewFranklin@gmail.com', fail_silently=False)
        print('sent')

and here's views.py

views.py

from django.shortcuts import render
from django.views.generic.edit import FormView
from .forms import ContactForm

...

class ContactView(FormView):
template_name = "main/contact.html"
form_class = ContactForm
success_url = '/thanks/'

def form_valid(self, form):
    ContactForm.send_email(form)
    return super(ContactView, self).form_valid(form)

1 Answers1

1

For starters, you're calling ContactForm.send_email which would only work if this was a class method (see here if you're interested about classmethods). You need to call send_email on the instance you created, form_class:

class ContactView(FormView):
    template_name = "main/contact.html"
    form_class = ContactForm
    success_url = '/thanks/'

    def form_valid(self, form):
        form_class.send_email(form)
        return super(ContactView, self).form_valid(form)

Beyond that, I would recommend verifying that the email server and settings are configured correctly. So, make sure you're able to send email from a simple python script.

Community
  • 1
  • 1
rofls
  • 4,993
  • 3
  • 27
  • 37