wip: saving submission with file attachments
authorAleksander Łukasz <aleksander.lukasz@nowoczesnapolska.org.pl>
Mon, 4 Nov 2013 09:34:27 +0000 (10:34 +0100)
committerAleksander Łukasz <aleksander.lukasz@nowoczesnapolska.org.pl>
Wed, 15 Jan 2014 10:18:53 +0000 (11:18 +0100)
wtem/forms.py [new file with mode: 0644]
wtem/migrations/0001_initial.py [new file with mode: 0644]
wtem/migrations/__init__.py [new file with mode: 0644]
wtem/models.py [new file with mode: 0644]
wtem/static/wtem/wtem.js
wtem/templates/wtem/exercises/file_upload.html
wtem/templates/wtem/main.html
wtem/templates/wtem/thanks.html [new file with mode: 0644]
wtem/urls.py
wtem/views.py

diff --git a/wtem/forms.py b/wtem/forms.py
new file mode 100644 (file)
index 0000000..61e1d7c
--- /dev/null
@@ -0,0 +1,32 @@
+import os
+
+from django import forms
+from django.utils import simplejson
+
+from .models import Submission, Attachment
+
+
+class WTEMForm(forms.ModelForm):
+    class Meta:
+        model = Submission
+        fields = ('answers',)
+
+    def __init__(self, *args, **kwargs):
+        super(WTEMForm, self).__init__(*args, **kwargs)
+
+        ## @@ move this one level up
+        f = file(os.path.dirname(__file__) + '/fixtures/exercises.json')
+        exercises = simplejson.loads(f.read())
+        f.close()
+
+        for exercise in exercises:
+            if exercise['type'] != 'file_upload':
+                continue
+            self.fields['attachment_' + exercise['name']] = forms.FileField(required = False)
+
+    def save(self):
+        submission = super(WTEMForm, self).save()
+        for file in self.files.values():
+            attachment = Attachment(file = file, submission = submission)
+            attachment.save()
+
diff --git a/wtem/migrations/0001_initial.py b/wtem/migrations/0001_initial.py
new file mode 100644 (file)
index 0000000..6d22934
--- /dev/null
@@ -0,0 +1,70 @@
+# -*- coding: utf-8 -*-
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+        # Adding model 'Submission'
+        db.create_table(u'wtem_submission', (
+            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+            ('contact', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contact.Contact'], null=True)),
+            ('key', self.gf('django.db.models.fields.CharField')(unique=True, max_length=30)),
+            ('first_name', self.gf('django.db.models.fields.CharField')(max_length=100)),
+            ('last_name', self.gf('django.db.models.fields.CharField')(max_length=100)),
+            ('email', self.gf('django.db.models.fields.EmailField')(unique=True, max_length=100)),
+            ('answers', self.gf('django.db.models.fields.CharField')(max_length=65536, null=True, blank=True)),
+        ))
+        db.send_create_signal(u'wtem', ['Submission'])
+
+        # Adding model 'Attachment'
+        db.create_table(u'wtem_attachment', (
+            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+            ('submission', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['wtem.Submission'])),
+            ('name', self.gf('django.db.models.fields.CharField')(max_length=100)),
+            ('file', self.gf('django.db.models.fields.files.FileField')(max_length=100)),
+        ))
+        db.send_create_signal(u'wtem', ['Attachment'])
+
+
+    def backwards(self, orm):
+        # Deleting model 'Submission'
+        db.delete_table(u'wtem_submission')
+
+        # Deleting model 'Attachment'
+        db.delete_table(u'wtem_attachment')
+
+
+    models = {
+        u'contact.contact': {
+            'Meta': {'ordering': "('-created_at',)", 'object_name': 'Contact'},
+            'body': ('jsonfield.fields.JSONField', [], {'default': '{}'}),
+            'contact': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
+            'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'form_tag': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}),
+            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'ip': ('django.db.models.fields.IPAddressField', [], {'max_length': '15'})
+        },
+        u'wtem.attachment': {
+            'Meta': {'object_name': 'Attachment'},
+            'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}),
+            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'submission': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['wtem.Submission']"})
+        },
+        u'wtem.submission': {
+            'Meta': {'object_name': 'Submission'},
+            'answers': ('django.db.models.fields.CharField', [], {'max_length': '65536', 'null': 'True', 'blank': 'True'}),
+            'contact': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contact.Contact']", 'null': 'True'}),
+            'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '100'}),
+            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}),
+            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+        }
+    }
+
+    complete_apps = ['wtem']
\ No newline at end of file
diff --git a/wtem/migrations/__init__.py b/wtem/migrations/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/wtem/models.py b/wtem/models.py
new file mode 100644 (file)
index 0000000..b6858cc
--- /dev/null
@@ -0,0 +1,52 @@
+import random
+import string
+
+from django.db import models
+
+from contact.models import Contact
+
+
+class Submission(models.Model):
+    contact = models.ForeignKey(Contact, null = True)
+    key = models.CharField(max_length = 30, unique = True)
+    first_name = models.CharField(max_length = 100)
+    last_name = models.CharField(max_length = 100)
+    email = models.EmailField(max_length = 100, unique = True)
+    answers = models.CharField(max_length = 65536, null = True, blank = True)
+
+    @classmethod
+    def generate_key(cls):
+        key = ''
+        while not key and key in [record['key'] for record in cls.objects.values('key')]:
+            key = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for i in range(30))
+        return key
+
+    @classmethod
+    def create(cls, first_name, last_name, email, contact = None, key = None):
+        submissions = []
+
+        if contact:
+            students = contact['students']
+        else:
+            students = [dict(first_name = first_name, last_name = last_name, email = email)]
+        
+        if key is None:
+            key = Submission.generate_key()
+
+        for student in students:
+            submission = cls(
+                contact = contact,
+                key = key,
+                first_name = student['first_name'],
+                last_name = student['last_name'],
+                email = student['email']
+            )
+            submission.save()
+            submissions.append(submission)
+        return submissions
+
+
+class Attachment(models.Model):
+    submission = models.ForeignKey(Submission)
+    name = models.CharField(max_length=100)
+    file = models.FileField(upload_to = 'wtem/attachment')
\ No newline at end of file
index 209108f..3f9bfad 100644 (file)
@@ -3,7 +3,7 @@ $(function() {
     var to_submit;
 
     $('#submit_answers').click(function(e) {
     var to_submit;
 
     $('#submit_answers').click(function(e) {
-        e.preventDefault();
+        //e.preventDefault();
         to_submit = [];
 
         $('.exercise-wtem').each(function() {
         to_submit = [];
 
         $('.exercise-wtem').each(function() {
@@ -18,7 +18,7 @@ $(function() {
             }
         });
         console.log(JSON.stringify(to_submit));
             }
         });
         console.log(JSON.stringify(to_submit));
-        $('input[name=wtem_answers]').val(JSON.stringify(to_submit));
+        $('input[name=answers]').val(JSON.stringify(to_submit));
     });
 
     var handlers = {
     });
 
     var handlers = {
index e4be9a1..df6f64b 100644 (file)
@@ -10,6 +10,6 @@
         {% endfor %}
     </div>
 
         {% endfor %}
     </div>
 
-    <input type="file"/>
+    <input type="file" name="attachment_{{exercise.name}}"/>
 
 </div>
\ No newline at end of file
 
 </div>
\ No newline at end of file
index 4536cfb..b3360b9 100644 (file)
@@ -9,7 +9,8 @@
 
 {% block body %}
 
 
 {% block body %}
 
-<form>
+<form method="post" enctype="multipart/form-data">
+{% csrf_token %}
 
 {% for exercise in exercises %}
     {% with 'wtem/exercises/'|add:exercise.type|add:'.html' as template_name %}
 
 {% for exercise in exercises %}
     {% with 'wtem/exercises/'|add:exercise.type|add:'.html' as template_name %}
@@ -19,7 +20,7 @@
 
 
 <hr/>
 
 
 <hr/>
-<input type="hidden" name="wtem_answers" value=""/>
+<input type="hidden" name="answers" value=""/>
 <button style="display: block; margin: auto;" id="submit_answers">Wyślij moje odpowiedzi</button>
 
 </form>
 <button style="display: block; margin: auto;" id="submit_answers">Wyślij moje odpowiedzi</button>
 
 </form>
diff --git a/wtem/templates/wtem/thanks.html b/wtem/templates/wtem/thanks.html
new file mode 100644 (file)
index 0000000..ca9463c
--- /dev/null
@@ -0,0 +1,7 @@
+{% extends 'base_super.html' %}
+
+{% block body %}
+
+<h1>Twoje rozwiązania zostały wysłane</h1>
+
+{% endblock %}
\ No newline at end of file
index 4fc156e..1dded94 100644 (file)
@@ -1,6 +1,8 @@
 from django.conf.urls import patterns, url
 from django.conf.urls import patterns, url
-from .views import main
+from django.conf import settings
+from .views import main, form
 
 urlpatterns = patterns('',
 
 urlpatterns = patterns('',
-    url(r'^$', main, name = 'wtem_main')
-)
\ No newline at end of file
+    url(r'^$', main, name = 'wtem_main'),
+    url(r'^(?P<key>.*)/$', form, name = 'wtem_form')
+)
index 6578e44..127710a 100644 (file)
@@ -2,12 +2,36 @@ import os
 
 from django.shortcuts import render
 from django.utils import simplejson
 
 from django.shortcuts import render
 from django.utils import simplejson
+from django.conf import settings
+from django.http import Http404
+
+from .models import Submission
+from .forms import WTEMForm
 
 
 def main(request):
 
 
 def main(request):
+    pass
+
+def form(request, key):
+    try:
+        submission = Submission.objects.get(key = key)
+    except Submission.DoesNotExist:
+        if settings.DEBUG and key == '12345':
+            submission = Submission.create(first_name = 'Debug', last_name = 'Debug', email = 'debug@debug.com', key = '12345')[0]
+        else:
+            raise Http404
+
     ## @@ move this out of the view
     f = file(os.path.dirname(__file__) + '/fixtures/exercises.json')
     exercises = simplejson.loads(f.read())
     f.close()
 
     ## @@ move this out of the view
     f = file(os.path.dirname(__file__) + '/fixtures/exercises.json')
     exercises = simplejson.loads(f.read())
     f.close()
 
-    return render(request, 'wtem/main.html', dict(exercises = exercises))
+    if request.method == 'GET':
+        return render(request, 'wtem/main.html', dict(exercises = exercises))
+    elif request.method == 'POST':
+        form = WTEMForm(request.POST, request.FILES, instance = submission)
+        if form.is_valid():
+            form.save()
+            return render(request, 'wtem/thanks.html')
+        else:
+            raise Exception