double break in workshop form
[prawokultury.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 from .models import Attachment, Contact
11
12
13 contact_forms = {}
14 admin_list_width = 0
15 class ContactFormMeta(forms.Form.__class__):
16     def __new__(cls, *args, **kwargs):
17         global admin_list_width
18         model = super(ContactFormMeta, cls).__new__(cls, *args, **kwargs)
19         assert model.form_tag not in contact_forms, 'Duplicate form_tag.'
20         if model.admin_list:
21             admin_list_width = max(admin_list_width, len(model.admin_list))
22         contact_forms[model.form_tag] = model
23         return model
24
25
26 class ContactForm(forms.Form):
27     """Subclass and define some fields."""
28     __metaclass__ = ContactFormMeta
29
30     started = False
31     form_tag = None
32     save_as_tag = None
33     form_title = _('Contact form')
34     submit_label = _('Submit')
35     admin_list = None
36     notify_on_register = True
37     notify_user = True
38
39     required_css_class = 'required'
40     contact = forms.EmailField(label=_('E-mail'), max_length=128)
41
42     def __init__(self, *args, **kwargs):
43         key = kwargs.pop('key', None)
44         super(ContactForm, self).__init__(*args, **kwargs)
45         self.key = key
46
47     def save(self, request):
48         key = self.key
49         body = {}
50         for name, value in self.cleaned_data.items():
51             if not isinstance(value, UploadedFile) and name != 'contact' and not name.startswith('_'):
52                     body[name] = value
53         save_as_tag = self.save_as_tag or self.form_tag
54         if key:
55             contact = Contact.objects.get(form_tag=save_as_tag, key=key)
56             contact.body = body
57             contact.ip = request.META['REMOTE_ADDR'] or '127.0.0.1'
58             contact.contact = self.cleaned_data['contact']
59             contact.save()
60         else:
61             contact = Contact.objects.create(body=body,
62                     ip=request.META['REMOTE_ADDR'],
63                     contact=self.cleaned_data['contact'],
64                     form_tag=save_as_tag)
65         for name, value in self.cleaned_data.items():
66             if isinstance(value, UploadedFile):
67                 contact.attachment_set.filter(tag=name).delete()
68                 attachment = Attachment(contact=contact, tag=name)
69                 attachment.file.save(value.name, value)
70                 attachment.save()
71
72         site = Site.objects.get_current()
73         dictionary = {
74             'form_tag': self.form_tag,
75             'site_name': site.name,
76             'site_domain': site.domain,
77             'contact': contact,
78             'form': self,
79         }
80         context = RequestContext(request)
81         if self.notify_on_register:
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             if self.notify_user:
98                 mail_subject = render_to_string([
99                         'contact/%s/mail_subject.txt' % self.form_tag,
100                         'contact/mail_subject.txt',
101                     ], dictionary, context).strip()
102                 mail_body = render_to_string([
103                         'contact/%s/mail_body.txt' % self.form_tag,
104                         'contact/mail_body.txt',
105                     ], dictionary, context)
106                 send_mail(mail_subject, mail_body,
107                     'no-reply@%s' % site.domain,
108                     [contact.contact],
109                     fail_silently=True)
110
111         return contact