Added complete support for dynamic form to add extra authors fields to proceedings form and added initial support for autocompletion based on user names for authors.
authorMadhusudan.C.S <madhusudancs@gmail.com>
Tue, 13 Jul 2010 01:01:02 +0530
changeset 101 fb27be005a5c
parent 100 60f67ccee452
child 102 16a406766773
Added complete support for dynamic form to add extra authors fields to proceedings form and added initial support for autocompletion based on user names for authors.
.hgignore
buildout.cfg
development.cfg
project/kiwipycon/proceedings/forms.py
project/kiwipycon/proceedings/views.py
project/kiwipycon/user/views.py
project/templates/proceedings/submit.html
project/urls.py
--- a/.hgignore	Tue May 11 03:51:25 2010 +0530
+++ b/.hgignore	Tue Jul 13 01:01:02 2010 +0530
@@ -39,5 +39,4 @@
 project/static/media
 project/kiwipycon/user/*.pyc
 apache/*
-project/static/proceedings/output/*
 
--- a/buildout.cfg	Tue May 11 03:51:25 2010 +0530
+++ b/buildout.cfg	Tue Jul 13 01:01:02 2010 +0530
@@ -51,8 +51,9 @@
     ${registration:location}
 
 [basic-apps]
-recipe = zerokspot.recipe.git
-repository = http://github.com/nathanborror/django-basic-apps.git
+recipe = infrae.subversion
+urls =
+    http://django-basic-apps.googlecode.com/svn/trunk/ basic
 
 [tagging]
 recipe = infrae.subversion
--- a/development.cfg	Tue May 11 03:51:25 2010 +0530
+++ b/development.cfg	Tue Jul 13 01:01:02 2010 +0530
@@ -2,8 +2,8 @@
 extends =
     buildout.cfg
 
-eggs +=
-    pysqlite
+#eggs +=
+#    pysqlite
 
 [django]
 settings = development
--- a/project/kiwipycon/proceedings/forms.py	Tue May 11 03:51:25 2010 +0530
+++ b/project/kiwipycon/proceedings/forms.py	Tue Jul 13 01:01:02 2010 +0530
@@ -27,4 +27,9 @@
 
     authors = forms.CharField(
         required=False, label=u'Author(s)',
-        help_text=u'Comma separated list of User ID of the author(s).')
+        help_text=u'User ID of the author.')
+
+    attachment = forms.FileField(
+        required=False, label=u'Attachments',
+        help_text=u'Attachments like images that must used in your paper '
+        'for rendering.')
--- a/project/kiwipycon/proceedings/views.py	Tue May 11 03:51:25 2010 +0530
+++ b/project/kiwipycon/proceedings/views.py	Tue Jul 13 01:01:02 2010 +0530
@@ -1,51 +1,23 @@
-  # -*- coding: utf-8 -*-
-
-import os
+# -*- coding: utf-8 -*-
+import json
 
 from django.contrib.auth import login
 from django.contrib.auth.decorators import login_required
 from django.contrib.auth.forms import AuthenticationForm
 from django.contrib.auth.models import User
-from django.core.urlresolvers import reverse
+from django.http import HttpResponse
 from django.shortcuts import render_to_response
 from django.template import RequestContext
-from django.utils import simplejson as json
 
-from project.kiwipycon.proceedings.booklet import mk_scipy_paper
-from project.kiwipycon.proceedings.forms import ProceedingsForm
-from project.kiwipycon.proceedings.models import Paper
 from project.kiwipycon.user.forms import RegisterForm
 from project.kiwipycon.user.models import UserProfile
-from project.kiwipycon.user.utils import kiwipycon_createuser
-from project.kiwipycon.utils import set_message_cookie
-from project import settings
-
-
-def handleUploadedFile(proceedings_form_data, rst_file):
-    """Handles the uploaded file content and process the form
-    """
-
-    title = proceedings_form_data.get('title')
-    abstract = proceedings_form_data.get('abstract')
-    body = proceedings_form_data.get('body')
-
-    if rst_file:
-        # TODO: using stating only for testing purposes.
-        destination = open('some/file/name.txt', 'wb+')
-        for chunk in rst_file.chunks():
-            destination.write(chunk)
-        destination.close()
-
-    return title, abstract, body
+from project.kiwipycon.proceedings.forms import ProceedingsForm
 
 
 @login_required
-def submit(request, id=None, template='proceedings/submit.html'):
+def submit(request, template = 'proceedings/submit.html'):
     """View to submit the proceedings paper.
     """
-
-    context = RequestContext(request, {})
-
     user = request.user
     if user.is_authenticated():
         try:
@@ -57,7 +29,10 @@
     message = None
 
     if request.method == 'POST':
-        register_form = RegisterForm(data=request.POST)
+        proceedings_form = ProceedingsForm(data=request.POST)
+
+        register_form = RegisterForm(data=request.POST,
+                                        files=request.FILES)
 
         if request.POST.get('action', None) == 'login':
             login_form = AuthenticationForm(data=request.POST)
@@ -72,141 +47,67 @@
         if request.POST.get('action', None) == 'register':
             # add the new user
             if register_form.is_valid():
+
                 user = kiwipycon_createuser(request, register_form.data)
 
-        proceedings_form = ProceedingsForm(data=request.POST,
-                                           files=request.FILES)
-
         if proceedings_form.is_valid():
             if user.is_authenticated():
-                # Data from reSt file is appended to the data in fields
-                title, abstract, body = handleUploadedFile(
-                    proceedings_form.cleaned_data, request.FILES.get('file'))
-                authors = request.POST.get('as_values_authors')
-
-                paper = edit(id, title=title,
-                    abstract=abstract, body=body,
-                    authors=authors) if id else create(title=title,
-                    abstract=abstract, body=body,
-                    authors=authors)
+                title = proceedings_form.data.get('title')
 
-                # Successfully saved. So get back to the edit page.
-                redirect_to = reverse('kiwipycon_submit_proceedings',
-                                  args=[paper.id])
-                return set_message_cookie(
-                redirect_to, msg = u'Thanks, your paper has been submitted.')
+                # Saved, ... redirect back to account
+                redirect_to = reverse('kiwipycon_account')
+                return set_message_cookie(redirect_to,
+                        msg = u'Thanks, your paper has been submitted.')
             else:
-                # This is impossible. Something was wrong so return back
-                # to submit page
                 redirect_to = reverse('kiwipycon_submit_proceedings')
-                return set_message_cookie(
-                redirect_to, msg = u'Something is wrong here.')          
+                return set_message_cookie(redirect_to,
+                        msg = u'Something is wrong here.')
+
     else:
-        if id:
-            # If id exists initialize the form with old values
-            paper = Paper.objects.get(id=id)
-            proceedings_form = ProceedingsForm(
-                initial={'title': paper.title,
-                         'abstract': paper.abstract,
-                         'body': paper.body,
-                })
-            context['initial_authors'] = json.dumps([
-                {'name': str(author.username),
-                 'value': '%s (%s)' % (author.get_full_name(), author.username)
-                } for author in paper.authors.all()])
-        else:
-            # Otherwise create a new form
-            proceedings_form = ProceedingsForm()
+        proceedings_form = ProceedingsForm()
+        register_form = RegisterForm()
+    login_form = AuthenticationForm()
 
-        register_form = RegisterForm()
-        login_form = AuthenticationForm()
+        
+    proceedings_form = ProceedingsForm()
+    register_form = RegisterForm()
+    login_form = AuthenticationForm()
 
-    context['proceedings_form'] = proceedings_form
-    context['register_form'] = register_form
-    context['message'] = message
-    context['login_form'] = login_form
-    context['id'] = id if id else None
+    context = RequestContext(request, {
+        'proceedings_form': proceedings_form,
+        'register_form' : register_form,
+        'message' : message,
+        'login_form' : login_form
+        })
 
     return render_to_response(template, context)
 
 
-def create(**kwargs):
-    """View to create a new proceedings.
-    """
-
-    title = kwargs.get('title')
-    abstract = kwargs.get('abstract')
-    body = kwargs.get('body')
-    authors = kwargs.get('authors')
-
-    paper = Paper(title=title, abstract=abstract, body=body)
-    paper.save()
-
-    if authors:
-        authors = authors.split(',')
-        for author in authors:
-            user = User.objects.get(username=author.strip())
-            paper.authors.add(user)
-
-    return paper
-
-
-def edit(id, **kwargs):
+def edit(request, id, template = 'proceedings/edit.html'):
     """View to edit the proceedings paper.
     """
 
-    paper = Paper.objects.get(id=id)
-
-    paper.title = kwargs.get('title')
-    paper.abstract = kwargs.get('abstract')
-    paper.body = kwargs.get('body')
-    authors = kwargs.get('authors')
+    context = RequestContext(request, {
+        'proceedings_form': proceedings_form,
+        'register_form' : register_form,
+        'message' : message,
+        'login_form' : login_form
+        })
 
-    if authors:
-        authors = authors.strip(' ,').split(',')
-        for author in authors:
-            user = User.objects.get(username=author.strip())
-            paper.authors.add(user)
-
-    paper.save()
-
-    return paper
+    return render_to_response(template, context)
 
 
-def show_paper(request, id):
-    """Display the thumbnail of the rendered paper for download
+def getUsers(request):
+    """View function called by autocomplete jQuery plugin to get
+    the user names.
     """
 
-    paper = Paper.objects.get(id=id)
+    query = request.GET['query']
+    suggestions = User.objects.filter(username__startswith=query)
+    
+    suggest_data = {
+        'query': query,
+        'suggestions':[user.username for user in suggestions],
+        }
 
-    # TODO: Address and country should be required field in the user forms
-    # henceforth. Also contact numbers.
-    paper_data = {
-      'paper_abstract': paper.abstract,
-      'authors': [
-          {'first_names': author.first_name,
-            'surname': author.last_name,
-            'address': 'None',
-            'country': 'India',
-            'email_address': author.email,
-            'institution': author.registration_set.get().organisation,
-            'city': author.registration_set.get().city
-           } for author in paper.authors.all()],
-      'title': paper.title
-      }
-
-    abstract = mk_scipy_paper.Bunch(**paper_data)
-    abstract.authors = [mk_scipy_paper.Bunch(**a) for a in abstract.authors]
-
-    abstract['paper_text'] = paper.body
-
-    out_dir = attach_dir = os.path.join(settings.STATIC_ROOT,
-                                        'proceedings', 'output')
-    outfilename = os.path.join(out_dir, 'paper%d.pdf' % (paper.id))
-    mk_scipy_paper.mk_abstract_preview(abstract, outfilename, attach_dir)
-
-    context = {'paper_id': paper.id,
-               'out_path': '/static/proceedings/output' }
-    template = 'proceedings/show_paper_preview.html'
-
-    return render_to_response(template, context)
+    return HttpResponse(json.dumps(suggest_data))
\ No newline at end of file
--- a/project/kiwipycon/user/views.py	Tue May 11 03:51:25 2010 +0530
+++ b/project/kiwipycon/user/views.py	Tue Jul 13 01:01:02 2010 +0530
@@ -1,23 +1,22 @@
 # -*- coding: utf-8 -*-
 from __future__ import absolute_import
-
 #python
 from urlparse import urlparse
+import urllib
 import os
 
 #django
 from django.conf import settings
+from django.shortcuts import render_to_response
+from django.template import RequestContext
+from django.core.urlresolvers import reverse
+from django.db.models.signals import post_save
+
+#django.contrib
 from django.contrib.auth.decorators import login_required
 from django.contrib.auth.forms import AuthenticationForm
 from django.contrib.auth.forms import PasswordChangeForm
-from django.contrib.auth.models import User
 from django.core.exceptions import ObjectDoesNotExist
-from django.core.urlresolvers import reverse
-from django.db.models import Q
-from django.http import HttpResponse
-from django.shortcuts import render_to_response
-from django.template import RequestContext
-from django.utils import simplejson as json
 
 #PIL
 from PIL import Image
@@ -28,6 +27,7 @@
 from project.kiwipycon.registration.models import Registration
 from project.kiwipycon.registration.models import Wifi
 from project.kiwipycon.registration.forms import WifiForm
+from project.kiwipycon.sponsor.models import Sponsor
 
 from .utils import kiwipycon_createuser
 from .utils import handle_uploaded_photo
@@ -57,6 +57,8 @@
     else:
         photo = '/img/user-default.png'
 
+    qstring = ""
+
     wifi_comment = None
     if wifiobj:
         wifi_form = False
@@ -234,32 +236,3 @@
         "form": username_form
     }))
 
-
-def get_usernames(request):
-    """Returns in json the list of ten possible usernames
-    starting with the last pattern in the comma separated string
-    """
-
-    get_params = request.GET
-    search_author = get_params.get('q')
-
-    if search_author:
-        search_author = search_author.strip()
-    else:
-        return HttpResponse(json.dumps(''))
-    
-
-    users = User.objects.filter(
-        Q(username__istartswith=search_author) | Q(
-        first_name__istartswith=search_author) | Q(
-        last_name__istartswith=search_author))
-
-    results = []
-    
-    for user in users:
-        results.append(
-            {'name': str(user.username),
-             'value': '%s (%s)' % (user.get_full_name(), user.username)
-            })
-
-    return HttpResponse(json.dumps(results))
--- a/project/templates/proceedings/submit.html	Tue May 11 03:51:25 2010 +0530
+++ b/project/templates/proceedings/submit.html	Tue Jul 13 01:01:02 2010 +0530
@@ -2,18 +2,18 @@
 {% block title %}Submit Paper for Proceedings{% endblock %}
 
 {% block addscripts %}
-<link rel="stylesheet" href="/static/css/autoSuggest.css" type="text/css" media="screen" charset="utf-8">
-<script type="text/javascript" src="/static/jquery/jquery.autoSuggest.js"></script>
-<script type="text/javascript">
-  $(document).ready(function() {
-    var initial_authors_obj = eval("{{ initial_authors|escapejs }}");
-    $("#id_authors").autoSuggest("{% url kiwipycon_get_usernames %}",
-                                 {minChars: 2, asHtmlID: "authors",
-                                  selectedValuesProp: "name",
-                                  preFill: initial_authors_obj });
-  });
-</script>
-
+  <link rel="stylesheet" type="text/css" href="/static/jquery/jquery.autocomplete.css" />
+  <script type="text/javascript" src="/static/jquery/jquery-ui-1.7.2.custom.min.js"></script>
+  <script type="text/javascript" src="/static/jquery/jquery-dynamic-form.js"></script>
+  <script type="text/javascript" src="/static/jquery/jquery.autocomplete-min.js"></script>
+  <script type="text/javascript">
+    $(document).ready(function(){	
+	  $("#author").dynamicForm("#plus", "#minus", {limit: 10, createColor: 'green',removeColor: 'red'});
+	  var a = $('input[id^=id_authors]').autocomplete({ 
+        serviceUrl:'/proceedings/getusers/', 
+      });
+	});
+  </script>
 {% endblock %}
 
 {% block content %}
@@ -21,7 +21,7 @@
 
   {% include '_errors.html' %}
 
-  <form action="{% if id %}{% url kiwipycon_submit_proceedings id %}{% else %}{% url kiwipycon_submit_proceedings %}{% endif %}" method="post">
+  <form action="{% url kiwipycon_submit_proceedings %}" method="post">
     {% if not user.is_authenticated %}
     <fieldset>
       <legend>Are you a member of this site?</legend>
@@ -31,8 +31,7 @@
     </fieldset>
   </form>
   <br />
-  <form action="{% url kiwipycon_submit_proceedings id %}" 
-    enctype="multipart/form-data" method="post">
+  <form action="{% url kiwipycon_submit_talk %}" enctype="multipart/form-data" method="post">
     <fieldset>
       <legend>User Registration</legend>
       <table class="kiwipycon-default required">{{ register_form }}</table>
@@ -59,13 +58,17 @@
         </tr>
         <tr>
           <th>{{ proceedings_form.rst_file.label }}</th>
-          <td>{{ proceedings_form.rst_file.errors }}
-              {{ proceedings_form.rst_file }}</td>
+          <td>{{ proceedings_form.rst_file.errors }}{{ proceedings_form.rst_file }}</td>
         </tr>
         <tr>
           <th>{{ proceedings_form.authors.label }}</th>
-          <td>{{ proceedings_form.authors.errors }}
-              {{ proceedings_form.authors }}</td>
+          <td>
+            <table style="position: relative; left: -3%;"><tr id="author"><td>
+            {{ proceedings_form.authors.errors }}
+            {{ proceedings_form.authors }}
+            <span><a id="minus" href="">[Remove]</a><a id="plus" href="">[Add]</a></span>
+            </td><tr></table>
+          </td>
         </tr>
       </table>
       <button class="button left" type="submit">Submit Paper</button>
--- a/project/urls.py	Tue May 11 03:51:25 2010 +0530
+++ b/project/urls.py	Tue Jul 13 01:01:02 2010 +0530
@@ -54,17 +54,13 @@
     url(r'^password/$', 'password', name='kiwipycon_password'), # change pwd
     url(r'^username/$', 'username', name='kiwipycon_username'), # change uname
     url(r'^edit-profile/$', 'edit_profile', name='kiwipycon_edit_profile'),
-    url(r'^get-usernames/$', 'get_usernames', name='kiwipycon_get_usernames'),
     )
 
 # Proceedings
 urlpatterns += patterns('project.kiwipycon.proceedings.views',
-    url(r'^proceedings/submit/$', 'submit',
-        name='kiwipycon_submit_proceedings'),
-    url(r'^proceedings/submit/(?P<id>\d+)/$', 'submit', 
-        name='kiwipycon_submit_proceedings'),
-    url(r'^proceedings/show_paper/(?P<id>\d+)/$', 'show_paper', 
-        name='kiwipycon_show_paper'),
+    url(r'^proceedings/submit/$',  'submit', name='kiwipycon_submit_proceedings'),
+    url(r'^proceedings/getusers/$',  'getUsers', name='kiwipycon_getusers_proceedings'),
+    url(r'^proceedings/edit/$',  'edit', name='kiwipycon_edit_proceedings'),
     )
 
 # About pages and all other static html pages