update registration 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
37     required_css_class = 'required'
38     contact = forms.CharField(max_length=128)
39
40     def __init__(self, *args, **kwargs):
41         key = kwargs.pop('key', None)
42         super(ContactForm, self).__init__(*args, **kwargs)
43         self.key = key
44
45     def save(self, request):
46         key = self.key
47         body = {}
48         for name, value in self.cleaned_data.items():
49             if not isinstance(value, UploadedFile) and name != 'contact' and not name.startswith('_'):
50                     body[name] = value
51         save_as_tag = self.save_as_tag or self.form_tag
52         if key:
53             contact = Contact.objects.get(form_tag=save_as_tag, key=key)
54             contact.body = body
55             contact.ip = request.META['REMOTE_ADDR'] or '127.0.0.1'
56             contact.contact = self.cleaned_data['contact']
57             contact.save()
58         else:
59             contact = Contact.objects.create(body=body,
60                     ip=request.META['REMOTE_ADDR'],
61                     contact=self.cleaned_data['contact'],
62                     form_tag=save_as_tag)
63         for name, value in self.cleaned_data.items():
64             if isinstance(value, UploadedFile):
65                 contact.attachment_set.filter(tag=name).delete()
66                 attachment = Attachment(contact=contact, tag=name)
67                 attachment.file.save(value.name, value)
68                 attachment.save()
69
70         site = Site.objects.get_current()
71         dictionary = {
72             'form_tag': self.form_tag,
73             'site_name': site.name,
74             'site_domain': site.domain,
75             'contact': contact,
76             'form': self,
77         }
78         context = RequestContext(request)
79         mail_managers_subject = render_to_string([
80                 'contact/%s/mail_managers_subject.txt' % self.form_tag,
81                 'contact/mail_managers_subject.txt', 
82             ], dictionary, context).strip()
83         mail_managers_body = render_to_string([
84                 'contact/%s/mail_managers_body.txt' % self.form_tag,
85                 'contact/mail_managers_body.txt', 
86             ], dictionary, context)
87         mail_managers(mail_managers_subject, mail_managers_body, 
88             fail_silently=True)
89
90         try:
91             validate_email(contact.contact)
92         except ValidationError:
93             pass
94         else:
95             mail_subject = render_to_string([
96                     'contact/%s/mail_subject.txt' % self.form_tag,
97                     'contact/mail_subject.txt', 
98                 ], dictionary, context).strip()
99             mail_body = render_to_string([
100                     'contact/%s/mail_body.txt' % self.form_tag,
101                     'contact/mail_body.txt', 
102                 ], dictionary, context)
103             send_mail(mail_subject, mail_body,
104                 'no-reply@%s' % site.domain,
105                 [contact.contact],
106                 fail_silently=True)
107
108         return contact