Anonymous avatar Anonymous committed 794aa30

added example_app, changed model names to reflect app naem

Comments (0)

Files changed (15)

emailform/admin.py

 from django.contrib import admin
 from django.forms import ModelForm, ValidationError
 
-from .models import Question, ContactForm, Entry
+from .models import Question, EmailForm, Entry
 
 
 class QuestionInline(admin.StackedInline):
     extra = 3
 
 
-class ContactFormAdminForm(ModelForm):
+class EmailFormAdminForm(ModelForm):
 
     class Meta:
-        model = ContactForm
+        model = EmailForm
 
 
-class ContactFormAdmin(admin.ModelAdmin):
+class EmailFormAdmin(admin.ModelAdmin):
     save_as = True
-    form = ContactFormAdminForm
+    form = EmailFormAdminForm
     search_fields = ('title', 'slug', 'description')
     prepopulated_fields = {'slug': ('title',)}
     list_display = (
     inlines = [QuestionInline]
 
 
-admin.site.register(ContactForm, ContactFormAdmin)
+admin.site.register(EmailForm, EmailFormAdmin)
 
 
 class EntryAdmin(admin.ModelAdmin):
     search_fields = ('content',)
-    list_display = ('contact_form', 'submitted_at',
+    list_display = ('emailform', 'submitted_at',
                     'ip_address', )
-    list_filter = ('contact_form', 'submitted_at', )
+    list_filter = ('emailform', 'submitted_at', )
     date_hierarchy = 'submitted_at'
 
 

emailform/forms.py

     )
 from django.forms.forms import BoundField
 
-from .models import OPTION_TYPE_CHOICES, ContactForm, Question, Entry
+from .models import OPTION_TYPE_CHOICES
 
 
 class BaseAnswerForm(Form):
 class BooleanInputAnswer(BaseAnswerForm):
     answer = BooleanField(initial=False)
 
-    def _configure_answer_field(self):
-        fld = super(BooleanInputAnswer, self)._configure_answer_field()
-        # we don't want to set this as required, as a single boolean field
-        # being required doesn't make much sense in a survey
-        fld.required = False
-        return fld
-
     def clean_answer(self):
         value = self.cleaned_data['answer']
         if not value:
     OPTION_TYPE_CHOICES.ZIPCODE:           USZipCodeAnswer}
 
 
-def forms_for_contact_form(contact_form, request='testing', entry=None):
+def forms_for_emailform(emailform, request='testing', entry=None):
     testing = 'testing' == request
     post = None if testing else request.POST or None
     files = None if testing else request.FILES or None
     return [_form_for_question(q, entry, post, files)
-        for q in contact_form.questions.all().order_by("order")]
+        for q in emailform.questions.all().order_by("order")]
 
 
 def _form_for_question(question,
     return QTYPE_FORM[question.option_type](
         question=question,
         entry=entry,
-        prefix='%s_%s' % (question.contact_form.id,
+        prefix='%s_%s' % (question.emailform.id,
                         question.id),
         data=data,
         files=files)

emailform/models.py

 from operator import itemgetter
 
 from django.contrib.sites.models import Site
+from django.core.urlresolvers import reverse
 from django.db import models
 from django.utils.translation import ugettext_lazy as _
 from django.contrib.sites.models import Site
 
 from .util import ChoiceEnum
 from . import settings as local_settings
-
 try:
     from positions.fields import PositionField
 except ImportError:
     PositionField = None
 
 
-class LiveContactFormManager(models.Manager):
+class LiveEmailFormManager(models.Manager):
 
     def get_query_set(self):
         now = datetime.datetime.now()
-        return super(LiveContactFormManager, self).get_query_set().filter(
+        return super(LiveEmailFormManager, self).get_query_set().filter(
             is_published=True,
             starts_at__lte=now)
 
 
-class ContactForm(models.Model):
+class EmailForm(models.Model):
 
     class Meta:
         ordering = ('-starts_at',)
     email = models.CharField(
         blank=True,
         help_text=_("Send a notification to this email whenever someone "
-                   "submits an entry to this contact form",),
+                   "submits an entry to this email form",),
         max_length=300)
     site = models.ForeignKey(Site)
 
         return self.title
 
     def get_url_path(self):
-        return ('contact_form_detail', (), {'slug': self.slug})
+        kwargs={'slug' : self.slug}
+        return reverse('emailform_detail',
+                       kwargs=kwargs)
 
     def get_full_url(self):
         url = self.get_url_path()
         site = self.site or Site.objects.get_current()
         return 'http://%s%s' % (site.domain, url)
 
-    @models.permalink
     def get_absolute_url(self):
         return self.get_full_url()
 
     objects = models.Manager()
-    live = LiveContactFormManager()
+    live = LiveEmailFormManager()
 
 OPTION_TYPE_CHOICES = ChoiceEnum(sorted([('char', 'Text Field'),
                                          ('email', 'Email Field'),
     class Meta:
         ordering = ('order',)
 
-    contact_form = models.ForeignKey(ContactForm, related_name="questions")
+    emailform = models.ForeignKey(EmailForm, related_name="questions")
     question = models.TextField(help_text=_(
-        "Appears on the contact form entry page."))
+        "Appears on the email form entry page."))
     label = models.CharField(max_length=32, help_text=_(
         "Appears on the results page."))
     help_text = models.TextField(blank=True)
     required = models.BooleanField(default=False)
     if PositionField:
-        order = PositionField(collection=('contact_form',))
+        order = PositionField(collection=('emailform',))
     else:
         order = models.IntegerField()
     option_type = models.CharField(max_length=12, choices=OPTION_TYPE_CHOICES)
         verbose_name_plural = "Entries"
         ordering = ('-submitted_at',)
 
-    contact_form = models.ForeignKey(ContactForm)
+    emailform = models.ForeignKey(EmailForm)
     ip_address = models.IPAddressField()
     submitted_at = models.DateTimeField(default=datetime.datetime.now)
     content = models.TextField(blank=True)

emailform/settings.py

 from django.conf import settings as _gs
 
 
-CONTACTFORM_EMAIL_FROM = getattr(_gs,
-                            'CONTACTFORM_EMAIL_FROM',
+EMAILFORM_EMAIL_FROM = getattr(_gs,
+                            'EMAILFORM_EMAIL_FROM',
                             'donotreply@donotreply.com')
 
 
-CONTACTFORM_ADMIN_SITE = getattr(_gs, 'CONTACTFORM_ADMIN_SITE', '')
+EMAILFORM_ADMIN_SITE = getattr(_gs, 'EMAILFORM_ADMIN_SITE', '')

emailform/urls.py

 
 from django.conf.urls.defaults import patterns, url
 
-from .views import contact_form_detail
+from .views import emailform_detail
 
 urlpatterns = patterns(
     "",
     url(r'^(?P<slug>[-a-z0-9_]+)/embed/$',
-        contact_form_detail,
+        emailform_detail,
         {'embed' : True},
-        name="contact_form_detail"),
+        name="emailform_detail"),
 
     url(r'^(?P<slug>[-a-z0-9_]+)/$',
-        contact_form_detail,
-        name="contact_form_detail"),
+        emailform_detail,
+        name="emailform_detail"),
     )

emailform/views.py

 from django.template import RequestContext as _rc
 from django.template.loader import render_to_string
 
-from .forms import forms_for_contact_form, BaseOptionAnswer
-from .models import ContactForm, Entry, OPTION_TYPE_CHOICES
+from .forms import forms_for_emailform, BaseOptionAnswer
+from .models import EmailForm, Entry, OPTION_TYPE_CHOICES
 
 from .util import ChoiceEnum
 from . import settings as local_settings
     return request.META['REMOTE_ADDR']
 
 
-def _get_contact_form_or_404(request, slug):
+def _get_emailform_or_404(request, slug):
     if request.user.is_staff:
-        return get_object_or_404(ContactForm.objects, slug=slug)
+        return get_object_or_404(EmailForm.objects, slug=slug)
     else:
-        return get_object_or_404(ContactForm.live, slug=slug)
+        return get_object_or_404(EmailForm.live, slug=slug)
 
 
-def _contact_form_submit(request, contact_form, embed=False):
-    forms = forms_for_contact_form(contact_form, request)
+def _emailform_submit(request, emailform, embed=False):
+    forms = forms_for_emailform(emailform, request)
     if all(form.is_valid() for form in forms):
         all_fields = []
         for field in forms:
                 if isinstance(field, BaseOptionAnswer):
                     v = ','.join(v)
                 all_fields.append('%s : %s' % (field.question.label, v))
-        entry = Entry(contact_form=contact_form,
+        entry = Entry(emailform=emailform,
                       ip_address=_get_remote_ip(request),
                       content=render_to_string(
-                        ('emailform/%s_completed_form.html'
-                         % (contact_form.slug),
-                        'emailform/completed_form.html'),
+                        ('emailform/%s_emailform_completed.html'
+                         % (emailform.slug),
+                        'emailform/emailform_completed.html'),
                         dict(all_fields=all_fields)))
         entry.save()
-        if contact_form.email:
-            _send_contact_form_email(request, contact_form, entry)
-        return _contact_form_show_form(request,
-                                       contact_form,
+        if emailform.email:
+            _send_emailform_email(request, emailform, entry)
+        return _emailform_show_form(request,
+                                       emailform,
                                        (),
                                        entered=True,
                                        embed=embed)
     else:
-        return _contact_form_show_form(request,
-                                       contact_form,
+        return _emailform_show_form(request,
+                                       emailform,
                                        forms,
                                        embed=embed)
 
     return admin_url + edit_url
 
 
-def _send_contact_form_email(request, contact_form, entry):
-    subject = contact_form.title
-    sender = local_settings.CONTACTFORM_EMAIL_FROM
-    recipients = list(set(x.strip() for x in contact_form.email.split(',')))
+def _send_emailform_email(request, emailform, entry):
+    subject = emailform.title
+    sender = local_settings.EMAILFORM_EMAIL_FROM
+    recipients = list(set(x.strip() for x in emailform.email.split(',')))
     links = [(_url_for_edit(request, entry), "Edit Submission"),
-             (_url_for_edit(request, contact_form), "Edit Contact Form"), ]
+             (_url_for_edit(request, emailform), "Edit Email Form"), ]
     html_email = entry.content
     email_msg = EmailMultiAlternatives(subject,
                                        html_email,
         logging.exception("Unexpected error sending email: %s" % str(ex))
 
 
-def _contact_form_show_form(request,
-                            contact_form,
+def _emailform_show_form(request,
+                            emailform,
                             forms,
                             entered=False,
                             embed=False):
     if embed:
-        specific_template = ('emailform/%s_contact_form_detail_embed.html' %
-                        contact_form.slug)
+        specific_template = ('emailform/%s_emailform_detail_embed.html' %
+                        emailform.slug)
         return render_to_response([specific_template,
-                               'emailform/contact_form_detail_embed.html'],
-                              dict(contact_form=contact_form,
+                               'emailform/emailform_detail_embed.html'],
+                              dict(emailform=emailform,
                                    forms=forms,
                                    entered=entered,
                                    embed=embed),
                               _rc(request))
-    specific_template = ('emailform/%s_contact_form_detail.html' %
-                    contact_form.slug)
+    specific_template = ('emailform/%s_emailform_detail.html' %
+                    emailform.slug)
     return render_to_response([specific_template,
-                           'emailform/contact_form_detail.html'],
-                          dict(contact_form=contact_form,
+                           'emailform/emailform_detail.html'],
+                          dict(emailform=emailform,
                                entered=entered,
                                forms=forms,
                                embed=embed),
                           _rc(request))
 
 
-def contact_form_detail(request, slug, embed=False):
-    contact_form = _get_contact_form_or_404(request, slug)
+def emailform_detail(request, slug, embed=False):
+    emailform = _get_emailform_or_404(request, slug)
     if request.method == 'POST':
-        return _contact_form_submit(request, contact_form, embed=embed)
-    forms = forms_for_contact_form(contact_form, request)
-    return _contact_form_show_form(request, contact_form, forms, embed=embed)
+        return _emailform_submit(request, emailform, embed=embed)
+    forms = forms_for_emailform(emailform, request)
+    return _emailform_show_form(request, emailform, forms, embed=embed)
Add a comment to this file

example_app/__init__.py

Empty file added.

Add a comment to this file

example_app/example_app_requirements.txt

Empty file added.

example_app/manage.py

+#!/usr/bin/env python
+import os
+import sys
+
+from django.core.management import execute_manager
+
+# to be able to import the crowdsourcing app
+sys.path.append(os.path.normpath(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+try:
+    import settings # Assumed to be in the same directory.
+except ImportError:
+    sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
+    sys.exit(1)
+
+if __name__ == "__main__":
+    execute_manager(settings)

example_app/settings.py

+# Django settings for example_app project.
+import os
+PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
+DEBUG = True
+TEMPLATE_DEBUG = DEBUG
+
+ADMINS = (
+    # ('Your Name', 'your_email@domain.com'),
+)
+
+MANAGERS = ADMINS
+
+DATABASE_ENGINE = 'sqlite3'           # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
+DATABASE_NAME = 'dev.db'             # Or path to database file if using sqlite3.
+DATABASE_USER = ''             # Not used with sqlite3.
+DATABASE_PASSWORD = ''         # Not used with sqlite3.
+DATABASE_HOST = ''             # Set to empty string for localhost. Not used with sqlite3.
+DATABASE_PORT = ''             # Set to empty string for default. Not used with sqlite3.
+
+# Local time zone for this installation. Choices can be found here:
+# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
+# although not all choices may be available on all operating systems.
+# If running in a Windows environment this must be set to the same as your
+# system time zone.
+TIME_ZONE = 'America/Chicago'
+
+# Language code for this installation. All choices can be found here:
+# http://www.i18nguy.com/unicode/language-identifiers.html
+LANGUAGE_CODE = 'en-us'
+
+SITE_ID = 1
+
+# If you set this to False, Django will make some optimizations so as not
+# to load the internationalization machinery.
+USE_I18N = True
+
+# Absolute path to the directory that holds media.
+# Example: "/home/media/media.lawrence.com/"
+MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
+
+# URL that handles the media served from MEDIA_ROOT. Make sure to use a
+# trailing slash if there is a path component (optional in other cases).
+# Examples: "http://media.lawrence.com", "http://example.com/media/"
+MEDIA_URL = '/media/'
+
+# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
+# trailing slash.
+# Examples: "http://foo.com/media/", "/media/".
+ADMIN_MEDIA_PREFIX = '/media/admin/'
+
+# Make this unique, and don't share it with anybody.
+SECRET_KEY = '9INH&*++4HJK:#*(&^BB#n@##5o0w45)i=ly'
+
+# List of callables that know how to import templates from various sources.
+TEMPLATE_LOADERS = (
+    'django.template.loaders.filesystem.load_template_source',
+    'django.template.loaders.app_directories.load_template_source',
+)
+
+MIDDLEWARE_CLASSES = (
+    'django.middleware.common.CommonMiddleware',
+    'django.contrib.sessions.middleware.SessionMiddleware',
+    'django.contrib.auth.middleware.AuthenticationMiddleware',
+)
+
+ROOT_URLCONF = 'example_app.urls'
+
+TEMPLATE_DIRS = (
+    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
+    # Always use forward slashes, even on Windows.
+    # Don't forget to use absolute paths, not relative paths.
+    os.path.join(PROJECT_ROOT, 'templates')
+)
+
+INSTALLED_APPS = (
+    'django.contrib.auth',
+    'django.contrib.contenttypes',
+    'django.contrib.sessions',
+    'django.contrib.sites',
+    'django.contrib.admin',
+    'emailform',
+)
+
+try:
+    from local_settings import *
+except ImportError:
+    pass

example_app/templates/emailform/emailform_completed.html

+<html>
+<body>
+<ul>
+{% for field in all_fields %}:
+    <li>{{field}}</li>
+{% endfor %}
+</ul>
+</body>
+</html>

example_app/templates/emailform/emailform_detail.html

+<h3>{{emailform.title}}</h3>
+<h4>{{emailform.description}}</h4>
+{% if entered %}
+  {{emailform.thanks_message}}
+{% else %}
+  {% if forms %}
+    <form method="POST" enctype="multipart/form-data">
+      {% for form in forms %}
+        {{form.as_p}}
+        {% if form.question.required %}
+            <span class="required">*required</span>
+        {% endif %}
+      {% endfor %}
+      <p><input class="submit" type="submit" value="Submit Survey" /></p>
+    </form>
+  {% endif %}
+{% endif %}

example_app/templates/mako/emailform/emailform_completed.html

+<html>
+<body>
+<ul>
+%for field in all_fields:
+    <li>${field}</li>
+%endfor
+</ul>
+</body>
+</html>

example_app/templates/mako/emailform/emailform_detail.html

+<h3>${emailform.title}</h3>
+<h4>${emailform.description}</h4>
+%if entered:
+  ${emailform.thanks_message}
+%else
+  %if forms:
+    <form method="POST" enctype="multipart/form-data">
+      %for form in forms:
+        ${form.as_p()}
+        %if form.question.required:
+            <span class="required">*required</span>
+        %endif
+      %endfor      
+      <p><input class="submit" type="submit" value="Submit Survey" /></p>
+    </form>
+  %endif
+%endif

example_app/urls.py

+from django.conf import settings
+from django.conf.urls.defaults import *
+from django.contrib import admin
+admin.autodiscover()
+
+urlpatterns = patterns('',
+    (r'^contact/', include('emailform.urls')),
+    # Uncomment the admin/doc line below and add 'django.contrib.admindocs' 
+    # to INSTALLED_APPS to enable admin documentation:
+    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),
+    (r'^admin/', include(admin.site.urls)),
+    (r'^%s(?P<path>.*)$' % settings.MEDIA_URL[1:],
+     'django.views.static.serve',
+     {'document_root': settings.MEDIA_ROOT}),
+)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.