diff bandmap/views.py @ 827:5103edd3acc4

Bandmap: initial version complete. Javascript queries server for band data. View created to handle query. Test created for view. Link added to map in sidebar. Template tweaks.
author Brian Neal <bgneal@gmail.com>
date Sat, 27 Sep 2014 19:41:41 -0500
parents d91356818cef
children b9973588af28
line wrap: on
line diff
--- a/bandmap/views.py	Sat Sep 27 15:14:47 2014 -0500
+++ b/bandmap/views.py	Sat Sep 27 19:41:41 2014 -0500
@@ -1,11 +1,17 @@
 """Views for the bandmap application.
 
 """
+import json
+
 from django.contrib.auth.decorators import login_required
 from django.shortcuts import redirect, render
 from django.contrib import messages as django_messages
+from django.http import HttpResponse
+from django.template.loader import render_to_string
+from django.core.cache import cache
 
 from bandmap.forms import BandForm
+from bandmap.models import BandEntry
 
 
 SUCCESS = "Successfully submitted {} for admin review. Thanks!"
@@ -35,3 +41,41 @@
     return render(request, 'bandmap/add.html', {
         'form': form,
         })
+
+
+def query(request):
+    """Retrieves the band map entries and returns them as JSON.
+
+    """
+    show_param = request.GET.get('show', 'all')
+    if show_param not in ['all', 'active', 'inactive']:
+        show_param = 'all'
+
+    # Do we have the results cached already?
+    cache_key = 'bandmap-results-{}'.format(show_param)
+    results = cache.get(cache_key)
+    if results:
+        return HttpResponse(results, content_type='application/json')
+
+    # Generate results
+    qs = BandEntry.objects.filter(is_approved=True)
+    if show_param == 'active':
+        qs = qs.filter(is_active=True)
+    elif show_param == 'inactive':
+        qs = qs.filter(is_active=False)
+
+    bands = []
+    for band in qs.iterator():
+        bands.append({
+            'name': band.name,
+            'url': band.url,
+            'lat': band.lat,
+            'lon': band.lon,
+            'note': render_to_string('bandmap/balloon.html', {'band': band}),
+        })
+    results = json.dumps(bands)
+
+    # Store in cache
+    cache.set(cache_key, results, 300)
+
+    return HttpResponse(results, content_type='application/json')