enable new forms
[edumed.git] / contact / forms.py
1 # -*- coding: utf-8 -*-
2 from django.contrib.sites.models import Site
3 from django.core.exceptions import ValidationError
4 from django.core.files.uploadedfile import UploadedFile
5 from django.core.mail import send_mail, mail_managers
6 from django.core.validators import validate_email
7 from django import forms
8 from django.template.loader import render_to_string
9 from django.template import RequestContext
10 from django.utils.translation import ugettext_lazy as _
11
12 from . import mailing
13
14
15 contact_forms = {}
16 admin_list_width = 0
17
18
19 class ContactFormMeta(forms.Form.__class__):
20     def __new__(cls, name, bases, attrs):
21         global admin_list_width
22         model = super(ContactFormMeta, cls).__new__(cls, name, bases, attrs)
23         if model.form_tag:
24             assert model.form_tag not in contact_forms, 'Duplicate form_tag.'
25             if model.admin_list:
26                 admin_list_width = max(admin_list_width, len(model.admin_list))
27             contact_forms[model.form_tag] = model
28         return model
29
30
31 class ContactForm(forms.Form):
32     """Subclass and define some fields."""
33     __metaclass__ = ContactFormMeta
34
35     form_tag = None
36     old_form_tags = []
37     form_title = _('Contact form')
38     submit_label = _('Submit')
39     admin_list = None
40     result_page = False
41     mailing_field = None
42     mailing = False
43     data_processing = None
44
45     required_css_class = 'required'
46     contact = NotImplemented
47
48     def save(self, request, formsets=None):
49         from .models import Attachment, Contact
50         body = {}
51         for name, value in self.cleaned_data.items():
52             if not isinstance(value, UploadedFile) and name != 'contact':
53                 body[name] = value
54
55         for formset in formsets or []:
56             for f in formset.forms:
57                 sub_body = {}
58                 for name, value in f.cleaned_data.items():
59                     if not isinstance(value, UploadedFile):
60                         sub_body[name] = value
61                 if sub_body:
62                     body.setdefault(f.form_tag, []).append(sub_body)
63
64         contact = Contact.objects.create(
65             body=body,
66             ip=request.META['REMOTE_ADDR'],
67             contact=self.cleaned_data['contact'],
68             form_tag=self.form_tag)
69         for name, value in self.cleaned_data.items():
70             if isinstance(value, UploadedFile):
71                 attachment = Attachment(contact=contact, tag=name)
72                 attachment.file.save(value.name, value)
73                 attachment.save()
74
75         site = Site.objects.get_current()
76         dictionary = {
77             'form_tag': self.form_tag,
78             'site_name': getattr(self, 'site_name', site.name),
79             'site_domain': getattr(self, 'site_domain', site.domain),
80             'contact': contact,
81         }
82         context = RequestContext(request)
83         mail_managers_subject = render_to_string([
84                 'contact/%s/mail_managers_subject.txt' % self.form_tag,
85                 'contact/mail_managers_subject.txt', 
86             ], dictionary, context).strip()
87         mail_managers_body = render_to_string([
88                 'contact/%s/mail_managers_body.txt' % self.form_tag,
89                 'contact/mail_managers_body.txt', 
90             ], dictionary, context)
91         mail_managers(mail_managers_subject, mail_managers_body, fail_silently=True)
92
93         try:
94             validate_email(contact.contact)
95         except ValidationError:
96             pass
97         else:
98             mail_subject = render_to_string([
99                     'contact/%s/mail_subject.txt' % self.form_tag,
100                     'contact/mail_subject.txt', 
101                 ], dictionary, context).strip()
102             if self.result_page:
103                 mail_body = render_to_string(
104                     'contact/%s/results_email.txt' % contact.form_tag,
105                     {
106                         'contact': contact,
107                         'results': self.results(contact),
108                     }, context)
109             else:
110                 mail_body = render_to_string([
111                         'contact/%s/mail_body.txt' % self.form_tag,
112                         'contact/mail_body.txt',
113                     ], dictionary, context)
114             send_mail(mail_subject, mail_body, 'no-reply@%s' % site.domain, [contact.contact], fail_silently=True)
115             if self.mailing or (self.mailing_field and self.cleaned_data[self.mailing_field]):
116                 email = self.cleaned_data['contact']
117                 mailing.subscribe(email)
118
119         return contact