dummy exercises (quick fix)
[edumed.git] / contact / forms.py
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
11
12 contact_forms = {}
13 admin_list_width = 0
14 class ContactFormMeta(forms.Form.__class__):
15     def __new__(cls, *args, **kwargs):
16         global admin_list_width
17         model = super(ContactFormMeta, cls).__new__(cls, *args, **kwargs)
18         assert model.form_tag not in contact_forms, 'Duplicate form_tag.'
19         if model.admin_list:
20             admin_list_width = max(admin_list_width, len(model.admin_list))
21         contact_forms[model.form_tag] = model
22         return model
23
24
25 class ContactForm(forms.Form):
26     """Subclass and define some fields."""
27     __metaclass__ = ContactFormMeta
28
29     form_tag = None
30     form_title = _('Contact form')
31     submit_label = _('Submit')
32     admin_list = None
33
34     required_css_class = 'required'
35     contact = forms.CharField(max_length=128)
36
37     def save(self, request, formsets=None):
38         from .models import Attachment, Contact
39         body = {}
40         for name, value in self.cleaned_data.items():
41             if not isinstance(value, UploadedFile) and name != 'contact':
42                 body[name] = value
43
44         for formset in formsets or []:
45             for f in formset.forms:
46                 sub_body = {}
47                 for name, value in f.cleaned_data.items():
48                     if not isinstance(value, UploadedFile):
49                         sub_body[name] = value
50                 if sub_body:
51                     body.setdefault(f.form_tag, []).append(sub_body)
52                 
53         contact = Contact.objects.create(body=body,
54                     ip=request.META['REMOTE_ADDR'],
55                     contact=self.cleaned_data['contact'],
56                     form_tag=self.form_tag)
57         for name, value in self.cleaned_data.items():
58             if isinstance(value, UploadedFile):
59                 attachment = Attachment(contact=contact, tag=name)
60                 attachment.file.save(value.name, value)
61                 attachment.save()
62
63         site = Site.objects.get_current()
64         dictionary = {
65             'form_tag': self.form_tag,
66             'site_name': getattr(self, 'site_name', site.name),
67             'site_domain': getattr(self, 'site_domain', site.domain),
68             'contact': contact,
69         }
70         context = RequestContext(request)
71         mail_managers_subject = render_to_string([
72                 'contact/%s/mail_managers_subject.txt' % self.form_tag,
73                 'contact/mail_managers_subject.txt', 
74             ], dictionary, context).strip()
75         mail_managers_body = render_to_string([
76                 'contact/%s/mail_managers_body.txt' % self.form_tag,
77                 'contact/mail_managers_body.txt', 
78             ], dictionary, context)
79         mail_managers(mail_managers_subject, mail_managers_body, 
80             fail_silently=True)
81
82         try:
83             validate_email(contact.contact)
84         except ValidationError:
85             pass
86         else:
87             mail_subject = render_to_string([
88                     'contact/%s/mail_subject.txt' % self.form_tag,
89                     'contact/mail_subject.txt', 
90                 ], dictionary, context).strip()
91             mail_body = render_to_string([
92                     'contact/%s/mail_body.txt' % self.form_tag,
93                     'contact/mail_body.txt', 
94                 ], dictionary, context)
95             send_mail(mail_subject, mail_body,
96                 'no-reply@%s' % site.domain,
97                 [contact.contact],
98                 fail_silently=True)
99
100         return contact