we can now create RawDocuments
authorSeth Woodworth <seth@sethish.com>
Wed, 28 Aug 2013 16:46:27 +0000 (12:46 -0400)
committerSeth Woodworth <seth@sethish.com>
Wed, 28 Aug 2013 16:46:27 +0000 (12:46 -0400)
karmaworld/apps/document_upload/views.py
karmaworld/apps/notes/models.py
karmaworld/settings/common.py
karmaworld/templates/partial/filepicker.html
karmaworld/urls.py

index 60f00ef0ef347811e7b0c0921b7fda097acd9fcc..5b7fe2eb7c49a6900a94ea2eb940bccd5568d098 100644 (file)
@@ -1 +1,58 @@
-# Create your views here.
+#!/usr/bin/env python
+# -*- coding:utf8 -*-
+# Copyright (C) 2013  FinalsClub Foundation
+
+import datetime
+
+from django.http import HttpResponse
+from django.views.generic import CreateView
+from django.views.generic.edit import ProcessFormView
+from django.views.generic.edit import ModelFormMixin
+
+from karmaworld.apps.document_upload.models import RawDocument
+from karmaworld.apps.document_upload.forms import RawDocumentForm
+
+def save_fp_upload(request):
+    r_d_f = RawDocumentForm(request.POST)
+    if r_d_f.is_valid():
+        model_instance = r_d_f.save(commit=False)
+        model_instance.uploaded_at = datetime.datetime.utcnow()
+        model_instance.save()
+        return HttpResponse({'success'})
+    else:
+        return HttpResponse(r_d_f.errors, status=400)
+
+
+
+class AjaxableResponseMixin(object):
+    """
+    Mixin to add AJAX support to a form.
+    Must be used with an object-based FormView (e.g. CreateView)
+    """
+    def render_to_json_response(self, context, **response_kwargs):
+        data = json.dumps(context)
+        response_kwargs['content_type'] = 'application/json'
+        return HttpResponse(data, **response_kwargs)
+
+    def form_invalid(self, form):
+        response = super(AjaxableResponseMixin, self).form_invalid(form)
+        if self.request.is_ajax():
+            return self.render_to_json_response(form.errors, status=400)
+        else:
+            return response
+
+    def form_valid(self, form):
+        # We make sure to call the parent's form_valid() method because
+        # it might do some processing (in the case of CreateView, it will
+        # call form.save() for example).
+        response = super(AjaxableResponseMixin, self).form_valid(form)
+        if self.request.is_ajax():
+            data = {
+                'pk': self.object.pk,
+            }
+            return self.render_to_json_response(data)
+        else:
+            return response
+
+class RawDocumentCreate(AjaxableResponseMixin, CreateView):
+    model = RawDocument
index 689b2a3802733a047a894c22009c1d79530c1ab3..b23bdcbcf5d4db492c4130ce0e74ef09c5a66763 100644 (file)
@@ -46,7 +46,7 @@ class Document(models.Model):
     # WARNING: This may throw an error on migration
     is_hidden       = models.BooleanField(default=False)
 
-    fp_note = django_filepicker.models.FPFileField(
+    fp_file = django_filepicker.models.FPFileField(
             upload_to='queue/%Y/%m/%j/',
             null=True, blank=True,
             help_text=u"An uploaded file reference from Filepicker.io")
index 078d3a8eefa243a26f36da3748bc0a17b17415a2..f476433f0ff0b9f6d8e360acf9f25b78ded4fc0d 100644 (file)
@@ -10,6 +10,10 @@ from sys import path
 
 from djcelery import setup_loader
 
+from karmaworld.secret.filepicker import FILEPICKER_API_KEY as fp_api
+
+FILEPICKER_API_KEY = fp_api
+
 
 ########## PATH CONFIGURATION
 # Absolute filesystem path to the Django project directory:
index 27a3ffc7f6844f810a7dd0d043ee8aaa4d9ffe61..4fc90f065d1b0c6b04f09e9ae1959f59054664b4 100644 (file)
@@ -34,7 +34,7 @@
     </div>
 
     <div id="form-template" class="row" style="display:none">
-      <form class="inline-form" method="POST">
+      <form class="inline-form" method="POST" action="{% url 'upload_post' %}">
         <div class="small-6 columns">
           <legend>Title of Note <small class="form">* Required</small></legend>
           <input type="text" class="intext" id="id_name" name="name"
           <input type="text" id="id_tags" name="tags" class="taggit-tags"
                 placeholder="shakespeare, econ, physics">
         </div>
+        <div class="hidden-fields" style="display:none;">
+          <input type="text" id="id_fpfile" name="fpfile" class="fpurl">
+          <input type="text" id="id_course" name="course" value="{{ course.id }}"
+            class="course_id">
+          {% csrf_token %}
+          <input type="text" class="csrf" value='{{ csrf_token }}'>
+        </div>
       </form>
     </div>
   </div>
@@ -65,6 +72,7 @@
         $(_form.children[0].children[0].children[1]).val(upFile.filename); // replace with upFile name
         _form.style.display = "inline";
         _form.id = null; // clear the unique id
+        $(_form.children[0].children[2].children[0]).val(upFile.url);
         document.getElementById('forms_container').appendChild(_form);
       };
 
               $dropzone.text("Uploading ("+percentage+"%)");
           }
       });
+      $('#save-btn').on('click', function(e){
+        $('.inline-form').each(function(i,el){
+            var name, tags, fpurl, course;
+            name = $(el).find('.intext').val();
+            fp_file = $(el).find('.fpurl').val();
+            tags = $(el).find('.taggit-tags').val();
+            course = $(el).find('.course_id').val();
+            csrf = $(el).find('.csrf').val();
+
+            $.post('{% url 'upload_post' %}', {
+              'name': name,
+              'fp_file': fp_file,
+              'tags': tags,
+              'course': course,
+              'csrfmiddlewaretoken': csrf,
+            });
+        });
+      });
     });
   // TODO: js to submit all forms as POST to NEW ENDPOINT
   // TODO: Cancel (x) for each upload
index 5de44f9adb6d83391677fcd4b109b3ecc1f8c744..cdb67bf0b1946c9be74884965c479f7a4d1045ef 100644 (file)
@@ -17,6 +17,8 @@ from karmaworld.apps.courses.views import school_list
 from karmaworld.apps.notes.views import NoteView
 from karmaworld.apps.notes.views import RawNoteDetailView
 from karmaworld.apps.notes.views import PDFView
+from karmaworld.apps.document_upload.views import RawDocumentCreate
+from karmaworld.apps.document_upload.views import save_fp_upload
 
 # See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#hooking-adminsite-instances-into-your-urlconf
 admin.autodiscover()
@@ -62,6 +64,8 @@ urlpatterns = patterns('',
     url(r'^media/(?P<path>.*)$', 'django.views.static.serve', 
             {'document_root': settings.MEDIA_ROOT, }),
 
+    # Filepicker upload
+    url(r'^api/upload$', save_fp_upload, name='upload_post'),
     # VIEW for displaying a single Course
     url(r'^' + SLUG.format('school_') + '/' + SLUG.format('') + '$',
         CourseDetailView.as_view(), name='course_detail'),