4e99528a3eceda224c108ecdc69d83a43ca084d0
[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         assert model.form_tag not in contact_forms, 'Duplicate form_tag.'
24         if model.admin_list:
25             admin_list_width = max(admin_list_width, len(model.admin_list))
26         contact_forms[model.form_tag] = model
27         return model
28
29
30 class ContactForm(forms.Form):
31     """Subclass and define some fields."""
32     __metaclass__ = ContactFormMeta
33
34     form_tag = None
35     old_form_tags = []
36     form_title = _('Contact form')
37     submit_label = _('Submit')
38     admin_list = None
39     result_page = False
40     mailing_field = None
41     mailing = False
42     data_processing = None
43
44     required_css_class = 'required'
45     contact = NotImplemented
46
47     def save(self, request, formsets=None):
48         from .models import Attachment, Contact
49         body = {}
50         for name, value in self.cleaned_data.items():
51             if not isinstance(value, UploadedFile) and name != 'contact':
52                 body[name] = value
53
54         for formset in formsets or []:
55             for f in formset.forms:
56                 sub_body = {}
57                 for name, value in f.cleaned_data.items():
58                     if not isinstance(value, UploadedFile):
59                         sub_body[name] = value
60                 if sub_body:
61                     body.setdefault(f.form_tag, []).append(sub_body)
62
63         contact = Contact.objects.create(
64             body=body,
65             ip=request.META['REMOTE_ADDR'],
66             contact=self.cleaned_data['contact'],
67             form_tag=self.form_tag)
68         for name, value in self.cleaned_data.items():
69             if isinstance(value, UploadedFile):
70                 attachment = Attachment(contact=contact, tag=name)
71                 attachment.file.save(value.name, value)
72                 attachment.save()
73
74         site = Site.objects.get_current()
75         dictionary = {
76             'form_tag': self.form_tag,
77             'site_name': getattr(self, 'site_name', site.name),
78             'site_domain': getattr(self, 'site_domain', site.domain),
79             'contact': contact,
80         }
81         context = RequestContext(request)
82         mail_managers_subject = render_to_string([
83                 'contact/%s/mail_managers_subject.txt' % self.form_tag,
84                 'contact/mail_managers_subject.txt', 
85             ], dictionary, context).strip()
86         mail_managers_body = render_to_string([
87                 'contact/%s/mail_managers_body.txt' % self.form_tag,
88                 'contact/mail_managers_body.txt', 
89             ], dictionary, context)
90         mail_managers(mail_managers_subject, mail_managers_body, fail_silently=True)
91
92         try:
93             validate_email(contact.contact)
94         except ValidationError:
95             pass
96         else:
97             mail_subject = render_to_string([
98                     'contact/%s/mail_subject.txt' % self.form_tag,
99                     'contact/mail_subject.txt', 
100                 ], dictionary, context).strip()
101             if self.result_page:
102                 mail_body = render_to_string(
103                     'contact/%s/results_email.txt' % contact.form_tag,
104                     {
105                         'contact': contact,
106                         'results': self.results(contact),
107                     }, context)
108             else:
109                 mail_body = render_to_string([
110                         'contact/%s/mail_body.txt' % self.form_tag,
111                         'contact/mail_body.txt',
112                     ], dictionary, context)
113             send_mail(mail_subject, mail_body, 'no-reply@%s' % site.domain, [contact.contact], fail_silently=True)
114             if self.mailing or (self.mailing_field and self.cleaned_data[self.mailing_field]):
115                 email = self.cleaned_data['contact']
116                 mailing.subscribe(email)
117
118         return contact