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