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)
42 site = Site.objects.get_current()
44 'form_tag': self.form_tag,
45 'site_name': site.name,
46 'site_domain': site.domain,
49 context = RequestContext(request)
50 mail_managers_subject = render_to_string([
51 'contact/%s/mail_managers_subject.txt' % self.form_tag,
52 'contact/mail_managers_subject.txt',
53 ], dictionary, context)
54 mail_managers_body = render_to_string([
55 'contact/%s/mail_managers_body.txt' % self.form_tag,
56 'contact/mail_managers_body.txt',
57 ], dictionary, context)
58 mail_managers(mail_managers_subject, mail_managers_body,
61 if email_re.match(contact.contact):
62 mail_subject = render_to_string([
63 'contact/%s/mail_subject.txt' % self.form_tag,
64 'contact/mail_subject.txt',
65 ], dictionary, context)
66 mail_body = render_to_string([
67 'contact/%s/mail_body.txt' % self.form_tag,
68 'contact/mail_body.txt',
69 ], dictionary, context)
70 send_mail(mail_subject, mail_body,
71 'no-reply@%s' % site.domain,