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 django.utils.translation import ugettext_lazy as _
9 from .models import Attachment, Contact
13 class ContactFormMeta(forms.Form.__metaclass__):
14 def __new__(cls, *args, **kwargs):
15 model = super(ContactFormMeta, cls).__new__(cls, *args, **kwargs)
16 assert model.form_tag not in contact_forms, 'Duplicate form_tag.'
17 contact_forms[model.form_tag] = model
21 class ContactForm(forms.Form):
22 """Subclass and define some fields."""
23 __metaclass__ = ContactFormMeta
26 form_title = _('Contact form')
27 submit_label = _('Submit')
29 required_css_class = 'required'
30 contact = forms.CharField(max_length=128)
32 def save(self, request):
34 for name, value in self.cleaned_data.items():
35 if not isinstance(value, UploadedFile) and name != 'contact':
37 contact = Contact.objects.create(body=body,
38 ip=request.META['REMOTE_ADDR'],
39 contact=self.cleaned_data['contact'],
40 form_tag=self.form_tag)
41 for name, value in self.cleaned_data.items():
42 if isinstance(value, UploadedFile):
43 attachment = Attachment(contact=contact, tag=name)
44 attachment.file.save(value.name, value)
47 site = Site.objects.get_current()
49 'form_tag': self.form_tag,
50 'site_name': site.name,
51 'site_domain': site.domain,
54 context = RequestContext(request)
55 mail_managers_subject = render_to_string([
56 'contact/%s/mail_managers_subject.txt' % self.form_tag,
57 'contact/mail_managers_subject.txt',
58 ], dictionary, context)
59 mail_managers_body = render_to_string([
60 'contact/%s/mail_managers_body.txt' % self.form_tag,
61 'contact/mail_managers_body.txt',
62 ], dictionary, context)
63 mail_managers(mail_managers_subject, mail_managers_body,
66 if email_re.match(contact.contact):
67 mail_subject = render_to_string([
68 'contact/%s/mail_subject.txt' % self.form_tag,
69 'contact/mail_subject.txt',
70 ], dictionary, context)
71 mail_body = render_to_string([
72 'contact/%s/mail_body.txt' % self.form_tag,
73 'contact/mail_body.txt',
74 ], dictionary, context)
75 send_mail(mail_subject, mail_body,
76 'no-reply@%s' % site.domain,