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 _
10 from .models import Attachment, Contact
15 class ContactFormMeta(forms.Form.__class__):
16 def __new__(cls, *args, **kwargs):
17 global admin_list_width
18 model = super(ContactFormMeta, cls).__new__(cls, *args, **kwargs)
19 assert model.form_tag not in contact_forms, 'Duplicate form_tag.'
21 admin_list_width = max(admin_list_width, len(model.admin_list))
22 contact_forms[model.form_tag] = model
26 class ContactForm(forms.Form):
27 """Subclass and define some fields."""
28 __metaclass__ = ContactFormMeta
33 form_title = _('Contact form')
34 submit_label = _('Submit')
37 required_css_class = 'required'
38 contact = forms.CharField(max_length=128)
40 def save(self, request):
42 for name, value in self.cleaned_data.items():
43 if not isinstance(value, UploadedFile) and name != 'contact':
45 save_as_tag = self.save_as_tag or self.form_tag
46 contact = Contact.objects.create(body=body,
47 ip=request.META['REMOTE_ADDR'],
48 contact=self.cleaned_data['contact'],
49 form_tag=self.save_as_tag)
50 for name, value in self.cleaned_data.items():
51 if isinstance(value, UploadedFile):
52 attachment = Attachment(contact=contact, tag=name)
53 attachment.file.save(value.name, value)
56 site = Site.objects.get_current()
58 'form_tag': self.form_tag,
59 'site_name': site.name,
60 'site_domain': site.domain,
64 context = RequestContext(request)
65 mail_managers_subject = render_to_string([
66 'contact/%s/mail_managers_subject.txt' % self.form_tag,
67 'contact/mail_managers_subject.txt',
68 ], dictionary, context)
69 mail_managers_body = render_to_string([
70 'contact/%s/mail_managers_body.txt' % self.form_tag,
71 'contact/mail_managers_body.txt',
72 ], dictionary, context)
73 mail_managers(mail_managers_subject, mail_managers_body,
77 validate_email(contact.contact)
78 except ValidationError:
81 mail_subject = render_to_string([
82 'contact/%s/mail_subject.txt' % self.form_tag,
83 'contact/mail_subject.txt',
84 ], dictionary, context)
85 mail_body = render_to_string([
86 'contact/%s/mail_body.txt' % self.form_tag,
87 'contact/mail_body.txt',
88 ], dictionary, context)
89 send_mail(mail_subject, mail_body,
90 'no-reply@%s' % site.domain,