Fixes.
[wolnelektury.git] / src / 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.urls import reverse
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     result_page = False
37
38     required_css_class = 'required'
39     # a subclass has to implement this field, but doing it here breaks the order
40     contact = NotImplemented
41
42     def save(self, request, formsets=None):
43         from .models import Attachment, Contact
44         body = {}
45         for name, value in self.cleaned_data.items():
46             if not isinstance(value, UploadedFile) and name != 'contact':
47                 body[name] = value
48
49         for formset in formsets or []:
50             for f in formset.forms:
51                 sub_body = {}
52                 for name, value in f.cleaned_data.items():
53                     if not isinstance(value, UploadedFile):
54                         sub_body[name] = value
55                 if sub_body:
56                     body.setdefault(f.form_tag, []).append(sub_body)
57
58         contact = Contact.objects.create(
59             body=body,
60             ip=request.META['REMOTE_ADDR'],
61             contact=self.cleaned_data['contact'],
62             form_tag=self.form_tag)
63         for name, value in self.cleaned_data.items():
64             if isinstance(value, UploadedFile):
65                 attachment = Attachment(contact=contact, tag=name)
66                 attachment.file.save(value.name, value)
67                 attachment.save()
68
69         site = Site.objects.get_current()
70         dictionary = {
71             'form_tag': self.form_tag,
72             'site_name': getattr(self, 'site_name', site.name),
73             'site_domain': getattr(self, 'site_domain', site.domain),
74             'contact': contact,
75         }
76         context = RequestContext(request)
77         mail_managers_subject = render_to_string([
78                 'contact/%s/mail_managers_subject.txt' % self.form_tag,
79                 'contact/mail_managers_subject.txt', 
80             ], dictionary, context).strip()
81         mail_managers_body = render_to_string([
82                 'contact/%s/mail_managers_body.txt' % self.form_tag,
83                 'contact/mail_managers_body.txt', 
84             ], dictionary, context)
85         mail_managers(mail_managers_subject, mail_managers_body, fail_silently=True)
86
87         try:
88             validate_email(contact.contact)
89         except ValidationError:
90             pass
91         else:
92             mail_subject = render_to_string([
93                     'contact/%s/mail_subject.txt' % self.form_tag,
94                     'contact/mail_subject.txt', 
95                 ], dictionary, context).strip()
96             if self.result_page:
97                 mail_body = render_to_string(
98                     'contact/%s/results_email.txt' % contact.form_tag,
99                     {
100                         'contact': contact,
101                         'results': self.results(contact),
102                     }, context)
103             else:
104                 mail_body = render_to_string([
105                         'contact/%s/mail_body.txt' % self.form_tag,
106                         'contact/mail_body.txt',
107                     ], dictionary, context)
108             send_mail(mail_subject, mail_body, 'no-reply@%s' % site.domain, [contact.contact], fail_silently=True)
109
110         return contact