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
14 class ContactFormMeta(forms.Form.__metaclass__):
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):
39 for name, value in self.cleaned_data.items():
40 if not isinstance(value, UploadedFile) and name != 'contact':
42 contact = Contact.objects.create(body=body,
43 ip=request.META['REMOTE_ADDR'],
44 contact=self.cleaned_data['contact'],
45 form_tag=self.form_tag)
46 for name, value in self.cleaned_data.items():
47 if isinstance(value, UploadedFile):
48 attachment = Attachment(contact=contact, tag=name)
49 attachment.file.save(value.name, value)
52 site = Site.objects.get_current()
54 'form_tag': self.form_tag,
55 'site_name': site.name,
56 'site_domain': site.domain,
59 context = RequestContext(request)
60 mail_managers_subject = render_to_string([
61 'contact/%s/mail_managers_subject.txt' % self.form_tag,
62 'contact/mail_managers_subject.txt',
63 ], dictionary, context)
64 mail_managers_body = render_to_string([
65 'contact/%s/mail_managers_body.txt' % self.form_tag,
66 'contact/mail_managers_body.txt',
67 ], dictionary, context)
68 mail_managers(mail_managers_subject, mail_managers_body,
71 if email_re.match(contact.contact):
72 mail_subject = render_to_string([
73 'contact/%s/mail_subject.txt' % self.form_tag,
74 'contact/mail_subject.txt',
75 ], dictionary, context)
76 mail_body = render_to_string([
77 'contact/%s/mail_body.txt' % self.form_tag,
78 'contact/mail_body.txt',
79 ], dictionary, context)
80 send_mail(mail_subject, mail_body,
81 'no-reply@%s' % site.domain,