a9e33665b06eb5d26471bc8051de7bd11b0696d8
[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.db.models.fields.files import FieldFile
9 from django.template.loader import render_to_string
10 from django.template import RequestContext
11 from django.utils.translation import ugettext_lazy as _
12
13 from . import mailing
14
15
16 contact_forms = {}
17 update_forms = {}
18 admin_list_width = 0
19
20
21 class ContactFormMeta(forms.Form.__class__):
22     def __new__(cls, name, bases, attrs):
23         global admin_list_width
24         model = super(ContactFormMeta, cls).__new__(cls, name, bases, attrs)
25         if model.form_tag:
26             if model.form_type == 'create':
27                 assert model.form_tag not in contact_forms, 'Duplicate form_tag.'
28                 if model.admin_list:
29                     admin_list_width = max(admin_list_width, len(model.admin_list))
30                 contact_forms[model.form_tag] = model
31             elif model.form_type == 'update':
32                 assert model.form_tag not in update_forms, 'Duplicate form_tag.'
33                 update_forms[model.form_tag] = model
34         return model
35
36
37 class ContactForm(forms.Form):
38     """Subclass and define some fields."""
39     __metaclass__ = ContactFormMeta
40
41     form_tag = None
42     form_type = 'create'
43     updatable = False
44     old_form_tags = []
45     form_title = _('Contact form')
46     submit_label = _('Submit')
47     admin_list = None
48     result_page = False
49     mailing_field = None
50     mailing = False
51     data_processing = None
52     form_formsets = {}
53
54     disabled = False
55     disabled_template = None
56
57     required_css_class = 'required'
58     contact = NotImplemented
59
60     def __init__(self, data=None, files=None, *args, **kwargs):
61         self.instance = kwargs.pop('instance', None)
62         if self.instance and (data is not None or files is not None):
63             for attachment in self.instance.attachment_set.all():
64                 if attachment.tag not in files:
65                     files[attachment.tag] = attachment.file
66         super(ContactForm, self).__init__(data, files, *args, **kwargs)
67         if not self.is_bound and self.instance:
68             self.fields['contact'].initial = self.instance.contact
69             body = self.instance.body
70             for field, value in body.iteritems():
71                 if field in self.fields:
72                     self.fields[field].initial = value
73             for attachment in self.instance.attachment_set.all():
74                 self.fields[attachment.tag].initial = attachment
75
76     def get_dictionary(self, contact):
77         site = Site.objects.get_current()
78         return {
79             'form_tag': self.form_tag,
80             'site_name': getattr(self, 'site_name', site.name),
81             'site_domain': getattr(self, 'site_domain', site.domain),
82             'contact': contact,
83         }
84
85     @classmethod
86     def is_disabled(cls):
87         # end_time = localtime_to_utc(datetime(*cls.ends_on)) if cls.ends_on else None
88         # expired = end_time and end_time < timezone.now()
89         return cls.disabled  # or expired
90
91     def formset_initial(self, prefix):
92         if not self.instance:
93             return None
94         return self.instance.body.get(prefix)
95
96     def get_formsets(self, request=None):
97         request_data = {'data': request.POST, 'files': request.FILES} if request else {}
98         kwargs_instance = dict(request_data)
99         kwargs_instance['instance'] = self.instance
100         formsets = {}
101         for prefix, formset_class in self.form_formsets.iteritems():
102             if getattr(formset_class, 'takes_instance', False):
103                 kwargs = kwargs_instance
104             else:
105                 kwargs = request_data
106             formsets[prefix] = formset_class(
107                 prefix=prefix, initial=self.formset_initial(prefix), **kwargs)
108         return formsets
109
110     def save(self, request, formsets=None):
111         from .models import Attachment, Contact
112         body = {}
113         for name, value in self.cleaned_data.items():
114             if not isinstance(value, UploadedFile) and not isinstance(value, FieldFile) and name != 'contact':
115                 body[name] = value
116
117         for formset in formsets or []:
118             for f in formset.forms:
119                 sub_body = {}
120                 for name, value in f.cleaned_data.items():
121                     if not isinstance(value, UploadedFile):
122                         sub_body[name] = value
123                 if sub_body:
124                     body.setdefault(f.form_tag, []).append(sub_body)
125
126         if self.instance:
127             contact = self.instance
128             contact.body = body
129             email_changed = contact.contact != self.cleaned_data['contact']
130             contact.contact = self.cleaned_data['contact']
131             assert contact.form_tag == self.form_tag
132             contact.save()
133         else:
134             contact = Contact.objects.create(
135                 body=body,
136                 ip=request.META['REMOTE_ADDR'],
137                 contact=self.cleaned_data['contact'],
138                 form_tag=self.form_tag)
139             contact.generate_key()
140             contact.save()
141             email_changed = True
142         for name, value in self.cleaned_data.items():
143             if isinstance(value, UploadedFile):
144                 Attachment.objects.filter(contact=contact, tag=name).delete()  # delete files?
145                 attachment = Attachment(contact=contact, tag=name)
146                 attachment.file.save(value.name, value)
147                 attachment.save()
148
149         site = Site.objects.get_current()
150         dictionary = self.get_dictionary(contact)
151         context = RequestContext(request)
152         mail_managers_subject = render_to_string([
153                 'contact/%s/mail_managers_subject.txt' % self.form_tag,
154                 'contact/mail_managers_subject.txt', 
155             ], dictionary, context).strip()
156         mail_managers_body = render_to_string([
157                 'contact/%s/mail_managers_body.txt' % self.form_tag,
158                 'contact/mail_managers_body.txt', 
159             ], dictionary, context)
160         mail_managers(mail_managers_subject, mail_managers_body, fail_silently=True)
161
162         try:
163             validate_email(contact.contact)
164         except ValidationError:
165             pass
166         else:
167             if not self.instance:
168                 mail_subject = render_to_string([
169                         'contact/%s/mail_subject.txt' % self.form_tag,
170                         'contact/mail_subject.txt',
171                     ], dictionary, context).strip()
172                 if self.result_page:
173                     mail_body = render_to_string(
174                         'contact/%s/results_email.txt' % contact.form_tag,
175                         {
176                             'contact': contact,
177                             'results': self.results(contact),
178                         }, context)
179                 else:
180                     mail_body = render_to_string([
181                             'contact/%s/mail_body.txt' % self.form_tag,
182                             'contact/mail_body.txt',
183                         ], dictionary, context)
184                 send_mail(mail_subject, mail_body, 'no-reply@%s' % site.domain, [contact.contact], fail_silently=True)
185             if email_changed and (self.mailing or (self.mailing_field and self.cleaned_data[self.mailing_field])):
186                 mailing.subscribe(contact.contact)
187
188         return contact