1 from django.contrib.sites.models import Site
2 from django.core.files.uploadedfile import UploadedFile
3 from django.core.mail import send_mail, mail_managers
4 from django.core.validators import email_re
5 from django import forms
6 from django.template.loader import render_to_string
7 from django.template import RequestContext
8 from .models import Attachment, Contact
12 class ContactFormMeta(forms.Form.__metaclass__):
13 def __new__(cls, *args, **kwargs):
14 model = super(ContactFormMeta, cls).__new__(cls, *args, **kwargs)
15 assert model.form_tag not in contact_forms, 'Duplicate form_tag.'
16 contact_forms[model.form_tag] = model
20 class ContactForm(forms.Form):
21 """Subclass and define some fields."""
22 __metaclass__ = ContactFormMeta
23 required_css_class = 'required'
24 contact = forms.CharField(max_length=128)
27 def save(self, request):
29 for name, value in self.cleaned_data.items():
30 if not isinstance(value, UploadedFile) and name != 'contact':
32 contact = Contact.objects.create(body=body,
33 ip=request.META['REMOTE_ADDR'],
34 contact=self.cleaned_data['contact'],
35 form_tag=self.form_tag)
36 for name, value in self.cleaned_data.items():
37 if isinstance(value, UploadedFile):
38 attachment = Attachment(contact=contact, tag=name)
39 attachment.file.save(value.name, value)
43 'form_tag': self.form_tag,
44 'site': Site.objects.get_current(),
48 context = RequestContext(request)
49 mail_managers_subject = render_to_string([
50 'contact/%s/mail_managers_subject.txt' % self.form_tag,
51 'contact/mail_managers_subject.txt',
52 ], dictionary, context)
53 mail_managers_body = render_to_string([
54 'contact/%s/mail_managers_body.txt' % self.form_tag,
55 'contact/mail_managers_body.txt',
56 ], dictionary, context)
57 mail_managers(mail_managers_subject, mail_managers_body,
60 if email_re.match(contact.contact):
61 mail_subject = render_to_string([
62 'contact/%s/mail_subject.txt' % self.form_tag,
63 'contact/mail_subject.txt',
64 ], dictionary, context)
65 mail_body = render_to_string([
66 'contact/%s/mail_body.txt' % self.form_tag,
67 'contact/mail_body.txt',
68 ], dictionary, context)
69 send_mail(mail_subject, mail_body,
70 'no-reply@%s' % dictionary['site'].domain,