refactor
[edumed.git] / contact / forms.py
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
10
11 contact_forms = {}
12 admin_list_width = 0
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.'
18         if model.admin_list:
19             admin_list_width = max(admin_list_width, len(model.admin_list))
20         contact_forms[model.form_tag] = model
21         return model
22
23
24 class ContactForm(forms.Form):
25     """Subclass and define some fields."""
26     __metaclass__ = ContactFormMeta
27
28     form_tag = None
29     form_title = _('Contact form')
30     submit_label = _('Submit')
31     admin_list = None
32
33     required_css_class = 'required'
34     contact = forms.CharField(max_length=128)
35
36     def save(self, request, formsets=None):
37         from .models import Attachment, Contact
38         body = {}
39         for name, value in self.cleaned_data.items():
40             if not isinstance(value, UploadedFile) and name != 'contact':
41                 body[name] = value
42
43         for formset in formsets or []:
44             for f in formset.forms:
45                 sub_body = {}
46                 for name, value in f.cleaned_data.items():
47                     if not isinstance(value, UploadedFile):
48                         sub_body[name] = value
49                 if sub_body:
50                     body.setdefault(f.form_tag, []).append(sub_body)
51                 
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)
60                 attachment.save()
61
62         site = Site.objects.get_current()
63         dictionary = {
64             'form_tag': self.form_tag,
65             'site_name': getattr(self, 'site_name', site.name),
66             'site_domain': getattr(self, 'site_domain', site.domain),
67             'contact': contact,
68         }
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, 
79             fail_silently=True)
80
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,
92                 [contact.contact],
93                 fail_silently=True)
94
95         return contact