Primary image for Django FormMail Clone

Django FormMail Clone

Here’s a little nugget I just posted to Django Snippets. It emulates the behavior of an old Perl script I used way back when, FormMail.pl.

I often find myself needing to build a form whose contents get emailed to the site owner(s). This class let’s you call form.notify() on any form that is a subclass of it to have the fields ordered and sent in a plain text email to all users that are flagged as staff.

from django import newforms as forms
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core.mail import send_mail

class FormMail(forms.Form):
def notify(self):
"""
Sends an email to all members of the staff with ordered list of fields
and values for any form that subclasses FormMail
"""
site_name = Site.objects.get_current().name
form_name = self.__class__.__name__
subject = '%s %s Submission' % (site_name, form_name)
user_list = [u.email for u in
User.objects.filter(is_staff=True).exclude(email="").order_by('id')]
message = ""
for k in self.base_fields.keyOrder:
message = message + '%s: %s\n\n' % (self[k].label, self.cleaned_data[k])
send_mail(subject, message, user_list[0], user_list)

## Example form
class ContactForm(FormMail):
name = forms.CharField()
phone = forms.CharField(required=False)
email = forms.EmailField()
comment = forms.CharField(widget=forms.Textarea())

## Example view code
form = ContactForm(request.POST)
if form.is_valid():
form.notify()
Peter Baumgartner

About the author

Peter Baumgartner

Peter is the founder of Lincoln Loop, having built it up from a small freelance operation in 2007 to what it is today. He is constantly learning and is well-versed in many technical disciplines including devops, …