import json
+from django.http import HttpResponse
from django.views.generic import DetailView
from django.views.generic import 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")
{% 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>
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 -->
# 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'),