Permalink
Browse files

added functionality to send email when form is valid

  • Loading branch information...
1 parent 3d857b2 commit 6b6e00a3b9e1e9c00853813647c9bf1d922b0e35 @madisona madisona committed Nov 20, 2010
Showing with 135 additions and 3 deletions.
  1. +36 −3 src/contact_form/forms.py
  2. +95 −0 src/contact_form/tests.py
  3. +4 −0 src/contact_form/views.py
View
@@ -1,6 +1,10 @@
from django import forms
+from django.conf import settings
+from django.template import loader, RequestContext
from django.core.mail import send_mail
+from django.contrib.sites.models import Site
+
from contact_form import models
@@ -9,6 +13,35 @@ class ContactForm(forms.ModelForm):
class Meta:
model = models.ContactEmail
- def save(self, *args, **kwargs):
- print("send the email sucka!")
- return super(ContactForm, self).save(*args, **kwargs)
+ from_email = settings.DEFAULT_FROM_EMAIL
+ recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS]
+
+ subject_template_name = "contact_form/email_subject.txt"
+ template_name = "contact_form/email_template.txt"
+
+ def get_message(self):
+ return loader.render_to_string(self.template_name, self.get_context())
+
+ def get_subject(self):
+ subject = loader.render_to_string(self.subject_template_name, self.get_context())
+ return ''.join(subject.splitlines())
+
+ def get_context(self):
+ if not self.is_valid():
+ raise ValueError("Cannot generate Context when form is invalid.")
+ return RequestContext(self.request, dict(
+ self.cleaned_data,
+ site=Site.objects.get_current(),
+ ))
+
+ def get_message_dict(self):
+ return {
+ "from_email": self.from_email,
+ "recipient_list": self.recipient_list,
+ "subject": self.get_subject(),
+ "message": self.get_message(),
+ }
+
+ def send_email(self, request, fail_silently=False):
+ self.request = request
+ send_mail(fail_silently=fail_silently, **self.get_message_dict())
View
@@ -2,12 +2,15 @@
"""
Contact Form tests
"""
+from mock import patch, Mock
from django import test
from django.core.urlresolvers import reverse
+from django.template import loader, TemplateDoesNotExist
from contact_form import views
from contact_form import models
+from contact_form import forms
class AcceptanceTestsContactPage(test.TestCase):
@@ -31,13 +34,20 @@ def should_have_contact_form_in_context(self):
response = self.client.get(reverse("contact_form:contact"))
self.assertTrue(isinstance(response.context['form'], views.ContactPage.form_class), "Form isn't present or isn't correct class")
+ @patch("contact_form.forms.ContactForm.send_email", Mock())
def should_create_contact_email_object_on_successful_form_post(self):
response = self.client.post(reverse("contact_form:contact"), self.email_data)
contact_email = models.ContactEmail.objects.get(pk=1)
self.assertEqual(self.email_data['name'], contact_email.name)
self.assertEqual(self.email_data['email'], contact_email.email)
self.assertEqual(self.email_data['message'], contact_email.message)
+ @patch("contact_form.forms.ContactForm.send_email")
+ def should_send_email_on_successful_form_post(self, send_email):
+ self.client.post(reverse("contact_form:contact"), self.email_data)
+ self.assertTrue(send_email.called, "Didn't send email on successful post")
+
+ @patch("contact_form.forms.ContactForm.send_email", Mock())
def should_redirect_to_complete_page_after_successful_post(self):
response = self.client.post(reverse("contact_form:contact"), self.email_data)
self.assertRedirects(response, reverse("contact_form:completed"))
@@ -51,3 +61,88 @@ def should_receive_200_status_code_for_completed_page(self):
def should_use_completed_template_when_rendering_page(self):
response = self.client.get(reverse("contact_form:completed"))
self.assertTemplateUsed(response, views.CompletedPage.template_name)
+
+class ContactFormTests(test.TestCase):
+
+ @patch("contact_form.forms.ContactForm.get_context", Mock())
+ @patch("django.template.loader.render_to_string")
+ def should_render_email_template_to_string(self, render_to_string):
+ form = forms.ContactForm()
+ message = form.get_message()
+ self.assertEqual([(form.template_name, form.get_context()), {}], render_to_string.call_args)
+ self.assertEqual(render_to_string.return_value, message)
+
+ @patch("contact_form.forms.ContactForm.get_context", Mock())
+ @patch("django.template.loader.render_to_string")
+ def should_render_subject_template_to_string(self, render_to_string):
+ render_to_string.return_value = "User has contacted you"
+ form = forms.ContactForm()
+ subject = form.get_subject()
+ self.assertEqual([(form.subject_template_name, form.get_context()), {}], render_to_string.call_args)
+ self.assertEqual(render_to_string.return_value, subject)
+
+ @patch("contact_form.forms.ContactForm.get_context", Mock())
+ @patch("django.template.loader.render_to_string")
+ def should_force_subject_to_be_one_line(self, render_to_string):
+ render_to_string.return_value = "User has \ncontacted you\n"
+ form = forms.ContactForm()
+ subject = form.get_subject()
+ self.assertEqual("User has contacted you", subject)
+
+ @patch("contact_form.forms.ContactForm.is_valid", Mock(return_value=False))
+ def should_receive_valid_error_if_form_is_invalid(self):
+ form = forms.ContactForm()
+ self.assertRaises(ValueError, form.get_context)
+
+ @patch("contact_form.forms.ContactForm.is_valid", Mock(return_value=True))
+ @patch("django.contrib.sites.models.Site.objects.get_current")
+ @patch("contact_form.forms.RequestContext")
+ def should_return_request_context_if_form_is_valid(self, request_context, current_site):
+ form = forms.ContactForm()
+ form.request = Mock()
+ form.cleaned_data = {'name': 'aaron'}
+
+ context = form.get_context()
+ self.assertEqual(request_context.return_value, context)
+ self.assertEqual([(form.request, {
+ 'name': 'aaron',
+ 'site': current_site.return_value,
+ }), {}], request_context.call_args)
+
+ @patch("contact_form.forms.send_mail")
+ @patch("contact_form.forms.ContactForm.get_message_dict")
+ def should_send_mail_with_message_dict(self, get_message_dict, send_mail):
+ get_message_dict.return_value = {"name": "aaron"}
+ form = forms.ContactForm()
+ form.send_email(Mock())
+
+ self.assertEqual([(), dict(get_message_dict.return_value, fail_silently=False)] , send_mail.call_args)
+
+ @patch("contact_form.forms.ContactForm.get_subject")
+ @patch("contact_form.forms.ContactForm.get_message")
+ def should_get_message_dict(self, get_message, get_subject):
+ form = forms.ContactForm()
+ message_dict = form.get_message_dict()
+
+ self.assertEqual({
+ "from_email": form.from_email,
+ "recipient_list": form.recipient_list,
+ "message": get_message.return_value,
+ "subject": get_subject.return_value,
+ }, message_dict)
+
+ def should_have_valid_subject_template(self):
+ template_exists = 1
+ try:
+ loader.render_to_string(forms.ContactForm.subject_template_name)
+ except TemplateDoesNotExist:
+ template_exists = 0
+ self.assertTrue(template_exists, "Subject template does not exist")
+
+ def should_have_valid_message_template(self):
+ template_exists = 1
+ try:
+ loader.render_to_string(forms.ContactForm.template_name)
+ except TemplateDoesNotExist:
+ template_exists = 0
+ self.assertTrue(template_exists, "Email message template does not exist")
@@ -11,5 +11,9 @@ class ContactPage(CreateView):
template_name = "contact_form/contact.html"
form_class = ContactForm
+ def form_valid(self, form):
+ form.send_email(self.request)
+ return super(ContactPage, self).form_valid(form)
+
def get_success_url(self):
return reverse("contact_form:completed")

0 comments on commit 6b6e00a

Please sign in to comment.