1 from django.contrib.sites.models import Site
2 from django.core.exceptions import ValidationError
3 from django.core.files.uploadedfile import UploadedFile
4 from django.core.mail import send_mail, mail_managers
5 from django.core.validators import validate_email
6 from django import forms
7 from django.template.loader import render_to_string
8 from django.template import RequestContext
9 from django.utils.translation import ugettext_lazy as _
14 class ContactFormMeta(forms.Form.__class__):
15 def __new__(cls, *args, **kwargs):
16 global admin_list_width
17 model = super(ContactFormMeta, cls).__new__(cls, *args, **kwargs)
18 assert model.form_tag not in contact_forms, 'Duplicate form_tag.'
20 admin_list_width = max(admin_list_width, len(model.admin_list))
21 contact_forms[model.form_tag] = model
25 class ContactForm(forms.Form):
26 """Subclass and define some fields."""
27 __metaclass__ = ContactFormMeta
30 form_title = _('Contact form')
31 submit_label = _('Submit')
34 required_css_class = 'required'
35 contact = forms.CharField(max_length=128)
37 def save(self, request, formsets=None):
38 from .models import Attachment, Contact
40 for name, value in self.cleaned_data.items():
41 if not isinstance(value, UploadedFile) and name != 'contact':
44 for formset in formsets or []:
45 for f in formset.forms:
47 for name, value in f.cleaned_data.items():
48 if not isinstance(value, UploadedFile):
49 sub_body[name] = value
51 body.setdefault(f.form_tag, []).append(sub_body)
53 contact = Contact.objects.create(body=body,
54 ip=request.META['REMOTE_ADDR'],
55 contact=self.cleaned_data['contact'],
56 form_tag=self.form_tag)
57 for name, value in self.cleaned_data.items():
58 if isinstance(value, UploadedFile):
59 attachment = Attachment(contact=contact, tag=name)
60 attachment.file.save(value.name, value)
63 site = Site.objects.get_current()
65 'form_tag': self.form_tag,
66 'site_name': getattr(self, 'site_name', site.name),
67 'site_domain': getattr(self, 'site_domain', site.domain),
70 context = RequestContext(request)
71 mail_managers_subject = render_to_string([
72 'contact/%s/mail_managers_subject.txt' % self.form_tag,
73 'contact/mail_managers_subject.txt',
74 ], dictionary, context).strip()
75 mail_managers_body = render_to_string([
76 'contact/%s/mail_managers_body.txt' % self.form_tag,
77 'contact/mail_managers_body.txt',
78 ], dictionary, context)
79 mail_managers(mail_managers_subject, mail_managers_body,
83 validate_email(contact.contact)
84 except ValidationError:
87 mail_subject = render_to_string([
88 'contact/%s/mail_subject.txt' % self.form_tag,
89 'contact/mail_subject.txt',
90 ], dictionary, context).strip()
91 mail_body = render_to_string([
92 'contact/%s/mail_body.txt' % self.form_tag,
93 'contact/mail_body.txt',
94 ], dictionary, context)
95 send_mail(mail_subject, mail_body,
96 'no-reply@%s' % site.domain,