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.db.models.fields.files import FieldFile
9 from django.template.loader import render_to_string
10 from django.template import RequestContext
11 from django.utils.translation import ugettext_lazy as _
21 class ContactFormMeta(forms.Form.__class__):
22 def __new__(cls, name, bases, attrs):
23 global admin_list_width
24 model = super(ContactFormMeta, cls).__new__(cls, name, bases, attrs)
26 if model.form_type == 'create':
27 assert model.form_tag not in contact_forms, 'Duplicate form_tag.'
29 admin_list_width = max(admin_list_width, len(model.admin_list))
30 contact_forms[model.form_tag] = model
31 elif model.form_type == 'update':
32 assert model.form_tag not in update_forms, 'Duplicate form_tag.'
33 update_forms[model.form_tag] = model
37 class ContactForm(forms.Form):
38 """Subclass and define some fields."""
39 __metaclass__ = ContactFormMeta
45 form_title = _('Contact form')
46 submit_label = _('Submit')
51 data_processing = None
55 disabled_template = None
57 required_css_class = 'required'
58 contact = NotImplemented
60 def __init__(self, data=None, files=None, *args, **kwargs):
61 self.instance = kwargs.pop('instance', None)
62 if self.instance and (data is not None or files is not None):
63 for attachment in self.instance.attachment_set.all():
64 if attachment.tag not in files:
65 files[attachment.tag] = attachment.file
66 super(ContactForm, self).__init__(data, files, *args, **kwargs)
67 if not self.is_bound and self.instance:
68 self.fields['contact'].initial = self.instance.contact
69 body = self.instance.body
70 for field, value in body.iteritems():
71 if field in self.fields:
72 self.fields[field].initial = value
73 for attachment in self.instance.attachment_set.all():
74 self.fields[attachment.tag].initial = attachment
76 def get_dictionary(self, contact):
77 site = Site.objects.get_current()
79 'form_tag': self.form_tag,
80 'site_name': getattr(self, 'site_name', site.name),
81 'site_domain': getattr(self, 'site_domain', site.domain),
87 # end_time = localtime_to_utc(datetime(*cls.ends_on)) if cls.ends_on else None
88 # expired = end_time and end_time < timezone.now()
89 return cls.disabled # or expired
91 def formset_initial(self, prefix):
94 return self.instance.body.get(prefix)
96 def get_formsets(self, request=None):
97 request_data = {'data': request.POST, 'files': request.FILES} if request else {}
98 kwargs_instance = dict(request_data)
99 kwargs_instance['instance'] = self.instance
101 for prefix, formset_class in self.form_formsets.iteritems():
102 if getattr(formset_class, 'takes_instance', False):
103 kwargs = kwargs_instance
105 kwargs = request_data
106 formsets[prefix] = formset_class(
107 prefix=prefix, initial=self.formset_initial(prefix), **kwargs)
110 def save(self, request, formsets=None):
111 from .models import Attachment, Contact
113 for name, value in self.cleaned_data.items():
114 if not isinstance(value, UploadedFile) and not isinstance(value, FieldFile) and name != 'contact':
117 for formset in formsets or []:
118 for f in formset.forms:
120 for name, value in f.cleaned_data.items():
121 if not isinstance(value, UploadedFile):
122 sub_body[name] = value
124 body.setdefault(f.form_tag, []).append(sub_body)
127 contact = self.instance
129 email_changed = contact.contact != self.cleaned_data['contact']
130 contact.contact = self.cleaned_data['contact']
131 assert contact.form_tag == self.form_tag
134 contact = Contact.objects.create(
136 ip=request.META['REMOTE_ADDR'],
137 contact=self.cleaned_data['contact'],
138 form_tag=self.form_tag)
139 contact.generate_key()
142 for name, value in self.cleaned_data.items():
143 if isinstance(value, UploadedFile):
144 Attachment.objects.filter(contact=contact, tag=name).delete() # delete files?
145 attachment = Attachment(contact=contact, tag=name)
146 attachment.file.save(value.name, value)
149 site = Site.objects.get_current()
150 dictionary = self.get_dictionary(contact)
151 context = RequestContext(request)
152 mail_managers_subject = render_to_string([
153 'contact/%s/mail_managers_subject.txt' % self.form_tag,
154 'contact/mail_managers_subject.txt',
155 ], dictionary, context).strip()
156 mail_managers_body = render_to_string([
157 'contact/%s/mail_managers_body.txt' % self.form_tag,
158 'contact/mail_managers_body.txt',
159 ], dictionary, context)
160 mail_managers(mail_managers_subject, mail_managers_body, fail_silently=True)
163 validate_email(contact.contact)
164 except ValidationError:
167 if not self.instance:
168 mail_subject = render_to_string([
169 'contact/%s/mail_subject.txt' % self.form_tag,
170 'contact/mail_subject.txt',
171 ], dictionary, context).strip()
173 mail_body = render_to_string(
174 'contact/%s/results_email.txt' % contact.form_tag,
177 'results': self.results(contact),
180 mail_body = render_to_string([
181 'contact/%s/mail_body.txt' % self.form_tag,
182 'contact/mail_body.txt',
183 ], dictionary, context)
184 send_mail(mail_subject, mail_body, 'no-reply@%s' % site.domain, [contact.contact], fail_silently=True)
185 if email_changed and (self.mailing or (self.mailing_field and self.cleaned_data[self.mailing_field])):
186 mailing.subscribe(contact.contact)