1 # -*- coding: utf-8 -*-
4 from django.contrib.sites.models import Site
5 from django.core.exceptions import ValidationError
6 from django.core.files.uploadedfile import UploadedFile
7 from django.core.mail import send_mail, mail_managers
8 from django.core.validators import validate_email
9 from django import forms
10 from django.db.models.fields.files import FieldFile
11 from django.template.loader import render_to_string
12 from django.template import RequestContext
13 from django.utils.translation import ugettext_lazy as _
23 class ContactFormMeta(forms.Form.__class__):
24 def __new__(cls, name, bases, attrs):
25 global admin_list_width
26 model = super(ContactFormMeta, cls).__new__(cls, name, bases, attrs)
28 if model.form_type == 'create':
29 assert model.form_tag not in contact_forms, 'Duplicate form_tag.'
31 admin_list_width = max(admin_list_width, len(model.admin_list))
32 contact_forms[model.form_tag] = model
33 elif model.form_type == 'update':
34 assert model.form_tag not in update_forms, 'Duplicate form_tag.'
35 update_forms[model.form_tag] = model
39 class ContactForm(forms.Form):
40 """Subclass and define some fields."""
41 __metaclass__ = ContactFormMeta
47 form_title = _('Contact form')
48 submit_label = _('Submit')
53 data_processing = None
57 disabled_template = None
59 required_css_class = 'required'
60 contact = NotImplemented
62 def __init__(self, data=None, files=None, *args, **kwargs):
63 self.instance = kwargs.pop('instance', None)
64 if self.instance and (data is not None or files is not None):
65 for attachment in self.instance.attachment_set.all():
66 if attachment.tag not in files:
67 files[attachment.tag] = attachment.file
68 super(ContactForm, self).__init__(data, files, *args, **kwargs)
69 if not self.is_bound and self.instance:
70 self.fields['contact'].initial = self.instance.contact
71 body = self.instance.body
72 for field, value in body.iteritems():
73 if field in self.fields:
74 self.fields[field].initial = value
75 for attachment in self.instance.attachment_set.all():
76 self.fields[attachment.tag].initial = attachment
78 def get_dictionary(self, contact):
79 site = Site.objects.get_current()
81 'form_tag': self.form_tag,
82 'site_name': getattr(self, 'site_name', site.name),
83 'site_domain': getattr(self, 'site_domain', site.domain),
89 # end_time = localtime_to_utc(datetime(*cls.ends_on)) if cls.ends_on else None
90 # expired = end_time and end_time < timezone.now()
91 return cls.disabled # or expired
93 def formset_initial(self, prefix):
96 return self.instance.body.get(prefix)
98 def get_formsets(self, request=None):
99 request_data = {'data': request.POST, 'files': request.FILES} if request else {}
100 kwargs_instance = dict(request_data)
101 kwargs_instance['instance'] = self.instance
103 for prefix, formset_class in self.form_formsets.iteritems():
104 if getattr(formset_class, 'takes_instance', False):
105 kwargs = kwargs_instance
107 kwargs = request_data
108 formsets[prefix] = formset_class(
109 prefix=prefix, initial=self.formset_initial(prefix), **kwargs)
112 def save(self, request, formsets=None):
113 from .models import Attachment, Contact
115 for name, value in self.cleaned_data.items():
116 if not isinstance(value, UploadedFile) and not isinstance(value, FieldFile) and name != 'contact':
119 for formset in formsets or []:
120 for f in formset.forms:
122 for name, value in f.cleaned_data.items():
123 if not isinstance(value, UploadedFile):
124 sub_body[name] = value
126 body.setdefault(f.form_tag, []).append(sub_body)
129 contact = self.instance
131 email_changed = contact.contact != self.cleaned_data['contact']
132 contact.contact = self.cleaned_data['contact']
133 assert contact.form_tag == self.form_tag
136 contact = Contact.objects.create(
138 ip=request.META['REMOTE_ADDR'],
139 contact=self.cleaned_data['contact'],
140 form_tag=self.form_tag)
141 contact.generate_key()
144 for name, value in self.cleaned_data.items():
145 if isinstance(value, UploadedFile):
146 for attachment in Attachment.objects.filter(contact=contact, tag=name):
147 os.remove(attachment.file.path)
149 attachment = Attachment(contact=contact, tag=name)
150 attachment.file.save(value.name, value)
153 site = Site.objects.get_current()
154 dictionary = self.get_dictionary(contact)
155 context = RequestContext(request)
156 mail_managers_subject = render_to_string([
157 'contact/%s/mail_managers_subject.txt' % self.form_tag,
158 'contact/mail_managers_subject.txt',
159 ], dictionary, context).strip()
160 mail_managers_body = render_to_string([
161 'contact/%s/mail_managers_body.txt' % self.form_tag,
162 'contact/mail_managers_body.txt',
163 ], dictionary, context)
164 mail_managers(mail_managers_subject, mail_managers_body, fail_silently=True)
167 validate_email(contact.contact)
168 except ValidationError:
171 if not self.instance:
172 mail_subject = render_to_string([
173 'contact/%s/mail_subject.txt' % self.form_tag,
174 'contact/mail_subject.txt',
175 ], dictionary, context).strip()
177 mail_body = render_to_string(
178 'contact/%s/results_email.txt' % contact.form_tag,
181 'results': self.results(contact),
184 mail_body = render_to_string([
185 'contact/%s/mail_body.txt' % self.form_tag,
186 'contact/mail_body.txt',
187 ], dictionary, context)
188 send_mail(mail_subject, mail_body, 'no-reply@%s' % site.domain, [contact.contact], fail_silently=True)
189 if email_changed and (self.mailing or (self.mailing_field and self.cleaned_data[self.mailing_field])):
190 mailing.subscribe(contact.contact)