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 _
13 class ContactFormMeta(forms.Form.__class__):
14 def __new__(cls, *args, **kwargs):
15 global admin_list_width
16 model = super(ContactFormMeta, cls).__new__(cls, *args, **kwargs)
17 assert model.form_tag not in contact_forms, 'Duplicate form_tag.'
19 admin_list_width = max(admin_list_width, len(model.admin_list))
20 contact_forms[model.form_tag] = model
24 class ContactForm(forms.Form):
25 """Subclass and define some fields."""
26 __metaclass__ = ContactFormMeta
29 form_title = _('Contact form')
30 submit_label = _('Submit')
33 required_css_class = 'required'
34 contact = forms.CharField(max_length=128)
36 def save(self, request, formsets=None):
37 from .models import Attachment, Contact
39 for name, value in self.cleaned_data.items():
40 if not isinstance(value, UploadedFile) and name != 'contact':
43 for formset in formsets or []:
44 for f in formset.forms:
46 for name, value in f.cleaned_data.items():
47 if not isinstance(value, UploadedFile):
48 sub_body[name] = value
50 body.setdefault(f.form_tag, []).append(sub_body)
52 contact = Contact.objects.create(body=body,
53 ip=request.META['REMOTE_ADDR'],
54 contact=self.cleaned_data['contact'],
55 form_tag=self.form_tag)
56 for name, value in self.cleaned_data.items():
57 if isinstance(value, UploadedFile):
58 attachment = Attachment(contact=contact, tag=name)
59 attachment.file.save(value.name, value)
62 site = Site.objects.get_current()
64 'form_tag': self.form_tag,
65 'site_name': getattr(self, 'site_name', site.name),
66 'site_domain': getattr(self, 'site_domain', site.domain),
69 context = RequestContext(request)
70 mail_managers_subject = render_to_string([
71 'contact/%s/mail_managers_subject.txt' % self.form_tag,
72 'contact/mail_managers_subject.txt',
73 ], dictionary, context).strip()
74 mail_managers_body = render_to_string([
75 'contact/%s/mail_managers_body.txt' % self.form_tag,
76 'contact/mail_managers_body.txt',
77 ], dictionary, context)
78 mail_managers(mail_managers_subject, mail_managers_body,
81 if email_re.match(contact.contact):
82 mail_subject = render_to_string([
83 'contact/%s/mail_subject.txt' % self.form_tag,
84 'contact/mail_subject.txt',
85 ], dictionary, context).strip()
86 mail_body = render_to_string([
87 'contact/%s/mail_body.txt' % self.form_tag,
88 'contact/mail_body.txt',
89 ], dictionary, context)
90 send_mail(mail_subject, mail_body,
91 'no-reply@%s' % site.domain,