Blog

Django FormMail Clone

Posted March 14, 2008. Filed under code, django

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

Need to get everyone on the same page? Try Ginger! Hold productive discussions with your teammates across the globe or across the hall. Build consensus, hash out complex ideas, and eliminate meetings altogether.

Looking for help building your web app? Lincoln Loop is a full service web studio focusing on Django development. See what we can do.

blog comments powered by Disqus