Autocomplete course names
authorCharles Connell <charles@connells.org>
Fri, 13 Dec 2013 22:01:40 +0000 (17:01 -0500)
committerCharles Connell <charles@connells.org>
Sat, 14 Dec 2013 22:53:23 +0000 (17:53 -0500)
karmaworld/apps/courses/views.py
karmaworld/assets/js/add-course.js
karmaworld/templates/partial/add_course.html
karmaworld/urls.py

index 717e24595493426d37bc0174170bf13c02b0b587..ab2c57e0e9e4b0a5f704867751e478921e8a54b3 100644 (file)
@@ -5,7 +5,10 @@
 
 import json
 
-from django.http import HttpResponse
+from django.core.exceptions import MultipleObjectsReturned
+from django.core.exceptions import ObjectDoesNotExist
+
+from django.http import HttpResponse, HttpResponseNotFound
 from django.views.generic import DetailView
 from django.views.generic import TemplateView
 from django.views.generic.edit import ProcessFormView
@@ -17,7 +20,6 @@ from karmaworld.apps.courses.models import Course
 from karmaworld.apps.courses.models import School
 from karmaworld.apps.notes.models import Note
 
-
 class CourseListView(ListView, ModelFormMixin, ProcessFormView):
     """ Simple ListView for the front page that includes the CourseForm """
     model = Course
@@ -102,3 +104,32 @@ def school_list(request):
     else:
         # else return that the api call failed
         return HttpResponse(json.dumps({'status':'fail'}), mimetype="application/json")
+
+
+def school_course_list(request):
+    """Return JSON describing courses we know of at the given school
+     that match the query """
+    if request.method == 'POST' and request.is_ajax() \
+                        and request.POST.has_key('q')\
+                        and request.POST.has_key('school_id'):
+
+        _query = request.POST['q']
+        try:
+          _school_id = int(request.POST['school_id'])
+        except:
+          return HttpResponseNotFound(json.dumps({'status': 'fail', 'message':'could not convert school id to integer'}), mimetype="application/json")
+
+        # Look up the school
+        try:
+            school = School.objects.get(id__exact=_school_id)
+        except (MultipleObjectsReturned, ObjectDoesNotExist):
+            return HttpResponseNotFound(json.dumps({'status': 'fail', 'message': 'school id did not match exactly one school'}), mimetype="application/json")
+
+        _courses = Course.objects.filter(school__exact=school.id, name__icontains=_query)
+        courses = [{'name': c.name} for c in _courses]
+
+        # return as json
+        return HttpResponse(json.dumps({'status':'success', 'courses': courses}), mimetype="application/json")
+    else:
+        # else return that the api call failed
+        return HttpResponseNotFound(json.dumps({'status': 'fail', 'message': 'query parameters missing'}), mimetype="application/json")
index 5aec0109b5d7c2ceee6b790aa01d70120051d8c5..f9f0e07c6b34c2cf9c91cbaae84e4802cba525cd 100644 (file)
@@ -9,6 +9,8 @@ $(function() {
     $('#add-course-form').show();
     // Hide the add a course button
     $('#add-course-btn').hide();
+    // Put focus in first input field
+    $('#str_school').focus();
   });
 
   // Set up the "Add Course" button in the
@@ -20,6 +22,7 @@ $(function() {
     $('#add-course-btn').hide();
     // Scroll the user's page to here
     $('#add-course-divider').ScrollTo();
+    // Put focus in first input field
     $('#str_school').focus();
   });
 
@@ -46,7 +49,7 @@ $(function() {
   $("#str_school").autocomplete({
     source: function(request, response){
       $.ajax({
-        url: json_course_list,
+        url: json_school_list,
         data: {q: request.term},
         success: function(data) {
           console.log(data);
@@ -83,4 +86,32 @@ $(function() {
     },
     minLength: 3
   });
+
+  $("#id_name").autocomplete({
+    source: function(request, response){
+      var school_id = $('#id_school').val()
+      $.ajax({
+        url: json_school_course_list,
+        data: {q: request.term, school_id: school_id},
+        success: function(data) {
+          console.log(data);
+          if (data['status'] === 'success') {
+            response($.map(data['courses'], function(item) {
+              return {
+                  value: item.name,
+                  label: item.name,
+              };
+            }));
+          } else {
+            // FIXME: do something?
+          }
+        },
+        dataType: "json",
+        type: 'POST'
+      });
+    },
+    minLength: 3
+  });
+
+
 });
index 99af04d39044ba72f0e910d767f91169310c5f8b..ea0c366499630b8d9a69f26330dc80729ae29f1b 100644 (file)
@@ -1,6 +1,7 @@
 {% load url from future %}
 <script>
-  var json_course_list = "{% url 'json_school_list' %}"
+  var json_school_list = "{% url 'json_school_list' %}"
+  var json_school_course_list = "{% url 'json_school_course_list' %}"
   var csrf_token = "{{ csrf_token }}";
 </script>
 <script src="{{ STATIC_URL }}js/add-course.js"></script>
index 6e0af643be468675054bc49eb33e6225c101655e..f69edd0c5641eff95faf3f0715d5862511e16f62 100644 (file)
@@ -14,6 +14,7 @@ from karmaworld.apps.courses.views import AboutView
 from karmaworld.apps.courses.views import CourseDetailView
 from karmaworld.apps.courses.views import CourseListView
 from karmaworld.apps.courses.views import school_list
+from karmaworld.apps.courses.views import school_course_list
 from karmaworld.apps.notes.views import NoteView
 from karmaworld.apps.notes.views import RawNoteDetailView
 from karmaworld.apps.notes.views import PDFView
@@ -88,6 +89,8 @@ urlpatterns = patterns('',
     url(r'^ajax-upload$', ajax_uploader, name='ajax_upload'),
     # return json list of schools
     url(r'^school/list/$', school_list, name='json_school_list'),
+    # return json list of courses for a given school
+    url(r'^school/course/list/$', school_course_list, name='json_school_course_list'),
     # ---- end JSON views ----#
 
     url(r'^$', CourseListView.as_view(model=Course), name='home'),