Running the old version.
[edumed.git] / contact / forms.py
index 73be1db..059f9e8 100644 (file)
@@ -1,10 +1,13 @@
 # -*- coding: utf-8 -*-
+import os
+
 from django.contrib.sites.models import Site
 from django.core.exceptions import ValidationError
 from django.core.files.uploadedfile import UploadedFile
 from django.core.mail import send_mail, mail_managers
 from django.core.validators import validate_email
 from django import forms
+from django.db.models.fields.files import FieldFile
 from django.template.loader import render_to_string
 from django.template import RequestContext
 from django.utils.translation import ugettext_lazy as _
@@ -39,6 +42,7 @@ class ContactForm(forms.Form):
 
     form_tag = None
     form_type = 'create'
+    updatable = False
     old_form_tags = []
     form_title = _('Contact form')
     submit_label = _('Submit')
@@ -47,20 +51,30 @@ class ContactForm(forms.Form):
     mailing_field = None
     mailing = False
     data_processing = None
+    form_formsets = {}
+
+    disabled = False
+    disabled_template = None
 
     required_css_class = 'required'
     contact = NotImplemented
 
-    def __init__(self, *args, **kwargs):
+    def __init__(self, data=None, files=None, *args, **kwargs):
         self.instance = kwargs.pop('instance', None)
-        super(ContactForm, self).__init__(*args, **kwargs)
+        if self.instance and (data is not None or files is not None):
+            for attachment in self.instance.attachment_set.all():
+                if attachment.tag not in files:
+                    files[attachment.tag] = attachment.file
+        super(ContactForm, self).__init__(data, files, *args, **kwargs)
         if not self.is_bound and self.instance:
-            # files are omitted (not necessary for now)
             self.fields['contact'].initial = self.instance.contact
+            self.fields['contact'].widget = forms.HiddenInput()
             body = self.instance.body
             for field, value in body.iteritems():
                 if field in self.fields:
                     self.fields[field].initial = value
+            for attachment in self.instance.attachment_set.all():
+                self.fields[attachment.tag].initial = attachment
 
     def get_dictionary(self, contact):
         site = Site.objects.get_current()
@@ -71,11 +85,36 @@ class ContactForm(forms.Form):
             'contact': contact,
         }
 
+    @classmethod
+    def is_disabled(cls):
+        # end_time = localtime_to_utc(datetime(*cls.ends_on)) if cls.ends_on else None
+        # expired = end_time and end_time < timezone.now()
+        return cls.disabled  # or expired
+
+    def formset_initial(self, prefix):
+        if not self.instance:
+            return None
+        return self.instance.body.get(prefix)
+
+    def get_formsets(self, request=None):
+        request_data = {'data': request.POST, 'files': request.FILES} if request else {}
+        kwargs_instance = dict(request_data)
+        kwargs_instance['instance'] = self.instance
+        formsets = {}
+        for prefix, formset_class in self.form_formsets.iteritems():
+            if getattr(formset_class, 'takes_instance', False):
+                kwargs = kwargs_instance
+            else:
+                kwargs = request_data
+            formsets[prefix] = formset_class(
+                prefix=prefix, initial=self.formset_initial(prefix), **kwargs)
+        return formsets
+
     def save(self, request, formsets=None):
         from .models import Attachment, Contact
         body = {}
         for name, value in self.cleaned_data.items():
-            if not isinstance(value, UploadedFile) and name != 'contact':
+            if not isinstance(value, UploadedFile) and not isinstance(value, FieldFile) and name != 'contact':
                 body[name] = value
 
         for formset in formsets or []:
@@ -100,10 +139,13 @@ class ContactForm(forms.Form):
                 ip=request.META['REMOTE_ADDR'],
                 contact=self.cleaned_data['contact'],
                 form_tag=self.form_tag)
+            contact.generate_key()
             email_changed = True
-        # not intended to be used with update forms
         for name, value in self.cleaned_data.items():
             if isinstance(value, UploadedFile):
+                for attachment in Attachment.objects.filter(contact=contact, tag=name):
+                    os.remove(attachment.file.path)
+                    attachment.delete()
                 attachment = Attachment(contact=contact, tag=name)
                 attachment.file.save(value.name, value)
                 attachment.save()