fixing school autocomplete for add course box
authorSeth Woodworth <seth@sethish.com>
Wed, 30 Jan 2013 00:39:51 +0000 (19:39 -0500)
committerSeth Woodworth <seth@sethish.com>
Wed, 30 Jan 2013 00:39:51 +0000 (19:39 -0500)
karmaworld/apps/courses/views.py
karmaworld/templates/lightbox/add_course.html
karmaworld/urls.py

index 5172bb5b1504e2f3cec4bb0a458cfc8bc7fa74a0..d35ede71e3c7cdb00ac221826727648f95a7af7d 100644 (file)
@@ -4,6 +4,7 @@
 
 import json
 
+from django.http import HttpResponse
 from django.views.generic import DetailView
 from django.views.generic import TemplateView
 
@@ -31,12 +32,14 @@ class AboutView(TemplateView):
 
 def school_list(request):
     """ Return JSON describing Schools that match q query on name """
-    if request.method == 'GET' and request.is_ajax() \
-                        and request.GET.has_key('q'):
+    if request.method == 'POST' and request.is_ajax() \
+                        and request.POST.has_key('q'):
         # if an ajax get request with a 'q' name query
-        # get the list of schools that match and return
-        schools = School.objects.filter(name__icontains=request.GET['q'])[:4]
-        return json.dump({'status':'success', 'schools': schools})
+        # get the schools as a id name dict,
+        schools = [{'id': s.id, 'name': s.name} for s in \
+              School.objects.filter(name__icontains=request.POST['q'])[:4]]
+        # return as json
+        return HttpResponse(json.dumps({'status':'success', 'schools': schools}), mimetype="application/json")
     else:
         # else return that the api call failed
-        return json.dump({'status':'fail'})
+        return HttpResponse(json.dump({'status':'fail'}), mimetype="application/json")
index dcfae1cc125a599dd470f21af664b2ee32a61e1b..8a5a712d4fdec8dcc1fded97c52fc2824e96d960 100644 (file)
@@ -1,16 +1,32 @@
 {% load url from future %}
 <script>
-    $("#id_school").autocomplete({
+$(function() {
+
+  function setupAjax(){
+    // Assumes variable csrf_token is made available
+    // by embedding document
+    $.ajaxSetup({
+          beforeSend: function(xhr, settings) {
+              if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
+                  // Only send the token to relative URLs i.e. locally.
+                  xhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}');
+              }
+          }
+    });
+  }
+
+  setupAjax();
+
+    $("#school").autocomplete({
         source: function(request, response){
             $.ajax({
                 url: "{% url 'json_school_list' %}",
                 data: {q: request.term},
                 success: function(data) {
-                    if (data['status'] === 'success')
-                    {
+                    console.log(data);
+                    if (data['status'] === 'success') {
                         response($.map(data['schools'], function(item) {
                             return {
-                                label: item.name,
                                 value: item.name,
                                 real_value: item.id
                             };
                 type: 'POST'
             });
         },
-        select: function(event, ui) { $('#id_school').val(ui.item.real_value); },
+        select: function(event, ui) { 
+            // set the school id as the value of the hidden field
+            $('#id_school').val(ui.item.real_value); 
+            // set the School name as the textbox ield
+            $('#school').val(ui.item.value);
+          },
         minLength: 3
     });
+});
 
 </script>
 
@@ -46,7 +68,8 @@
             School
           </label><!-- lightbox_label -->
           <div class="lightbox_field">
-            <input id="id_school" class="lightbox_textfield" type="text" name="school"/>
+            <input id="school" class="lightbox_textfield" type="text" name="school"/>
+            <input id="id_school" type='hidden'/>
           </div><!-- .lightbox_filed -->
         </div><!--  -->
       </div> <!-- .row .lightbox_row -->
index 49a2861cef06a019020f2f0e983dd27928ab18c3..c100163698ed4a2e6a004441879c146ba865cfba 100644 (file)
@@ -45,7 +45,7 @@ urlpatterns = patterns('',
     # uploading files
     url(r'^ajax-upload$', ajax_uploader, name='ajax_upload'),
     # return json list of schools
-    url(r'^j/school/list$', school_list, name='json_school_list'),
+    url(r'^school/list/$', school_list, name='json_school_list'),
     # ---- end JSON views ----#
 
     url(r'^$', ListView.as_view(model=Course), name='home'),