Permalink
Browse files

initial import

  • Loading branch information...
digi604 committed May 15, 2009
0 parents commit 5d4482d9ac49c9ea331e7bb331bf53d591cda850
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>dbforms</name>
+ <comment></comment>
+ <projects>
+ <project>django</project>
+ <project>dlib</project>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.python.pydev.PyDevBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.python.pydev.pythonNature</nature>
+ </natures>
+</projectDescription>
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse-pydev version="1.0"?>
+
+<pydev_project>
+<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.5</pydev_property>
+<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Default</pydev_property>
+<pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH">
+<path>/dbforms</path>
+</pydev_pathproperty>
+</pydev_project>
No changes.
@@ -0,0 +1,28 @@
+from django.contrib import admin
+from django.contrib.admin.options import TabularInline
+
+from dbforms.models import Form, Recipient, FormField, FormSubmission
+
+class FormFieldInline(TabularInline):
+ model = FormField
+ num_in_admin = 4
+ extra = 4
+ max_num = 40
+
+class FormAdmin(admin.ModelAdmin):
+ inlines = [
+ FormFieldInline,
+ ]
+ list_display = ('name', 'language',)
+ list_filter = ('language',)
+ search_fields = ('name',)
+ ordering = ('id', 'language',)
+
+class FormSubmissionAdmin(admin.ModelAdmin):
+ list_display = ('__unicode__', 'submitted_at', 'language', 'sender_ip',)
+ list_filter = ('form', 'language',)
+ search_fields = ('form_data',)
+
+admin.site.register(Form, FormAdmin)
+admin.site.register(Recipient)
+admin.site.register(FormSubmission, FormSubmissionAdmin)
@@ -0,0 +1,107 @@
+from django.utils.translation import ugettext_lazy as _
+from django.template.loader import render_to_string
+from django.utils.safestring import mark_safe
+
+from cms.plugin_pool import plugin_pool
+from cms.plugin_base import CMSPluginBase
+from contactform.models import ContactFormIntermediate, ContactFormSubmission
+from django.template.context import Context
+from django.template.defaultfilters import slugify, yesno
+from django.contrib.sites.models import Site
+from django.template import loader
+from django.core.mail import EmailMessage
+from django.conf import settings
+from pprint import pprint
+
+class ContactFormPlugin(CMSPluginBase):
+ model = ContactFormIntermediate
+ name = _("Contact Form")
+ placeholders = ("content",)
+ render_template = "contactform/form.html"
+ form_template = "contactform/plugin_form.html"
+
+ def render(self, context, instance, placeholder):
+ request = context['request']
+ contact_form = instance.form
+ FormClass = contact_form.get_form_class()
+ my_context = Context({
+ 'placeholder': placeholder,
+ 'contact_form': contact_form,
+ 'form_instance': FormClass(),
+ 'current_page': request.current_page,
+ 'page': request.current_page,
+ })
+ if request.method == 'POST' and "contactform_id" in request.POST \
+ and request.POST['contactform_id'] == str(contact_form.id):
+ # process the submitted form
+ form = FormClass(request.POST, request.FILES)
+ if form.is_valid():
+ site = Site.objects.get_current()
+ try:
+ from siteinfo.models import SiteSettings
+ contact = SiteSettings.objects.get_current()
+ except:
+ contact = None
+ subject = u"[%s] %s" % (site.domain, _(u"Contact form sent"))
+ print site.domain
+ # render fields
+ rows = ''
+ files = []
+ to_pickle = {}
+ for field in contact_form.field_set.all():
+ field_label = slugify(field.get_label())
+ value = form.cleaned_data[field_label]
+ if isinstance(value, bool):
+ value = yesno(value, u"%s,%s" % (_('yes'), _('no')),)
+ if field.field_type == 'FileField':
+ if field_label in request.FILES:
+ this_file = request.FILES[field_label]
+ if this_file.size > 10240: # check if file is bigger than 10 MB (which is not good)
+ files.append(this_file)
+ rows += u"%s: %s\n" % (form.fields[field_label].label, value)
+ to_pickle[unicode(field_label)] = unicode(value)
+ # use the verbose fieldname instead
+ #to_pickle[form.fields[field_label].label] = value
+ #pprint(to_pickle)
+
+ message_context = Context({
+ 'site': site,
+ 'form': form,
+ 'contact_form': contact_form,
+ 'rows': rows,
+ 'sender_ip': request.META['REMOTE_ADDR'],
+ 'form_url': request.build_absolute_uri(),
+ }, autoescape=False)
+ text_template = loader.get_template('contactform/form_email.txt')
+ text_content = text_template.render(message_context)
+ recipient_list = [recipient['email'] for recipient in contact_form.recipients.values('email')]
+ bcc = []
+ if contact_form.cc_managers:
+ bcc += [manager[1] for manager in settings.MANAGERS]
+ if contact_form.cc_site_contact and contact:
+ bcc += [contact.email]
+ message = EmailMessage(subject=subject, body=text_content, from_email=settings.DEFAULT_FROM_EMAIL, to=recipient_list, bcc=bcc)
+ for file in files:
+ message.attach(file.name, file.read(2621440), file.content_type)
+ message.send()
+ my_context.update({
+ 'form_instance': form,
+ 'success': mark_safe(contact_form.success_message.strip() or _("Your request has been submitted. We will process it as soon as possible.")),
+ })
+ # save message to db for later reference
+ submission = ContactFormSubmission(
+ form=contact_form,
+ sender_ip=request.META['REMOTE_ADDR'],
+ form_url=request.build_absolute_uri(),
+ language=contact_form.language,
+ form_data=text_content,
+ form_data_pickle=to_pickle)
+ submission.save()
+ else:
+ my_context.update({
+ 'form_instance': form,
+ 'contact_form': contact_form,
+ })
+ return my_context
+
+plugin_pool.register_plugin(ContactFormPlugin)
@@ -0,0 +1,69 @@
+# Generate CSV files for models
+from django.utils.encoding import smart_str, smart_unicode
+from django.db.models.fields.related import ManyToManyField
+import re
+from django.db.models.loading import get_model, get_apps, get_models
+from django.db.models import BooleanField
+from django.contrib.admin.views.decorators import staff_member_required
+from django.http import Http404, HttpResponse
+from django.shortcuts import render_to_response
+from django.template.defaultfilters import yesno
+
+from csv_export.views import _field_extractor_function, UnicodeWriter, DatabaseInconsistency
+
+from pprint import pprint
+
+@staff_member_required
+def export(request, app_label='contactform', model_name='contactformsubmission'):
+ """Return a CSV file for this table."""
+
+ # Get the fields of the table
+ model = get_model(app_label, model_name)
+ if not model:
+ raise Http404
+ fields1 = model._meta.fields
+ fields = []
+ for f in fields1:
+ if not f.name in ['form_data', 'form_data_pickle']:
+ fields.append(f)
+ field_funcs = [ _field_extractor_function(f) for f in fields ]
+
+ # set the HttpResponse
+ response = HttpResponse(mimetype='text/csv;charset=ISO-8859-1')
+ response['Content-Disposition'] = 'attachment; filename=%s-%s.csv' % (app_label, model_name)
+ writer = UnicodeWriter(response, encoding='iso8859-1', illegal_char_replacement='?')
+
+
+ # Do some simple query string check for filters
+ filters = {}
+ for param_name, param_value in request.REQUEST.items():
+ if re.match(r'.+__(exact|lte|gte|year|month)', param_name):
+ filters[str(param_name)] = param_value
+ # Write all rows of the CSV file
+ model_objects = model.objects.all().filter(**filters)
+ #pprint.pprint(model_objects)
+ # collect all the extra fields
+ extra_fieldnames = []
+ for o in model_objects:
+ extra_fields = o.form_data_pickle or {}
+ for key, value in extra_fields.items():
+ #print key, value
+ if not key in extra_fieldnames:
+ extra_fieldnames.append(key)
+ # Write the header of the CSV file
+ writer.writerow([ f.verbose_name for f in fields ] + extra_fieldnames )
+
+ for o in model_objects:
+ try:
+ row = [ func(o) for func in field_funcs ]
+ extra_fields = o.form_data_pickle or {}
+ for fn in extra_fieldnames:
+ if fn in extra_fields.keys():
+ row += [ extra_fields[fn] ]
+ else:
+ row += [ '' ]
+ writer.writerow(row)
+ except Exception, e:
+ raise DatabaseInconsistency,"there was an error at object %s (%s)" % ( o.id, e )
+ # All done
+ return response
@@ -0,0 +1,46 @@
+# -*- coding: utf-8 -*-
+from django.db import models
+
+try:
+ import cPickle as pickle
+except ImportError:
+ import pickle
+
+class PickledObject(str):
+ """A subclass of string so it can be told whether a string is
+ a pickled object or not (if the object is an instance of this class
+ then it must [well, should] be a pickled one)."""
+ pass
+
+class PickledObjectField(models.Field):
+ __metaclass__ = models.SubfieldBase
+
+ def to_python(self, value):
+ if isinstance(value, PickledObject):
+ # If the value is a definite pickle; and an error is raised in de-pickling
+ # it should be allowed to propogate.
+ return pickle.loads( str(value).decode('base64') )
+ else:
+ try:
+ return pickle.loads( str(value).decode('base64') )
+ except:
+ # If an error was raised, just return the plain value
+ return value
+
+ def get_db_prep_save(self, value):
+ if value is not None and not isinstance(value, PickledObject):
+ value = PickledObject( pickle.dumps(value).encode('base64') )
+ return value
+
+ def get_internal_type(self):
+ return 'TextField'
+
+ def get_db_prep_lookup(self, lookup_type, value):
+ if lookup_type == 'exact':
+ value = self.get_db_prep_save(value)
+ return super(PickledObjectField, self).get_db_prep_lookup(lookup_type, value)
+ elif lookup_type == 'in':
+ value = [self.get_db_prep_save(v) for v in value]
+ return super(PickledObjectField, self).get_db_prep_lookup(lookup_type, value)
+ else:
+ raise TypeError('Lookup type %s is not supported.' % lookup_type)
Binary file not shown.
Oops, something went wrong.

0 comments on commit 5d4482d

Please sign in to comment.