bgneal@820: """Views for the bandmap application. bgneal@820: bgneal@820: """ bgneal@827: import json bgneal@827: bgneal@820: from django.contrib.auth.decorators import login_required bgneal@820: from django.shortcuts import redirect, render bgneal@821: from django.contrib import messages as django_messages bgneal@827: from django.http import HttpResponse bgneal@827: from django.template.loader import render_to_string bgneal@827: from django.core.cache import cache bgneal@820: bgneal@820: from bandmap.forms import BandForm bgneal@827: from bandmap.models import BandEntry bgneal@820: bgneal@820: bgneal@821: SUCCESS = "Successfully submitted {} for admin review. Thanks!" bgneal@821: bgneal@821: bgneal@820: def map_view(request): bgneal@820: return render(request, 'bandmap/map.html') bgneal@820: bgneal@820: bgneal@820: @login_required bgneal@820: def add_band(request): bgneal@820: """ bgneal@820: Provides the ability for a user to submit a new band to the map. bgneal@820: bgneal@820: """ bgneal@820: if request.method == 'POST': bgneal@820: form = BandForm(request.POST) bgneal@820: if form.is_valid(): bgneal@820: band = form.save(commit=False) bgneal@820: band.user = request.user bgneal@820: band.save() bgneal@821: django_messages.success(request, SUCCESS.format(band.name)) bgneal@825: return redirect('bandmap-add') bgneal@820: else: bgneal@820: form = BandForm() bgneal@820: bgneal@820: return render(request, 'bandmap/add.html', { bgneal@820: 'form': form, bgneal@820: }) bgneal@827: bgneal@827: bgneal@827: def query(request): bgneal@827: """Retrieves the band map entries and returns them as JSON. bgneal@827: bgneal@827: """ bgneal@827: show_param = request.GET.get('show', 'all') bgneal@827: if show_param not in ['all', 'active', 'inactive']: bgneal@827: show_param = 'all' bgneal@827: bgneal@827: # Do we have the results cached already? bgneal@827: cache_key = 'bandmap-results-{}'.format(show_param) bgneal@827: results = cache.get(cache_key) bgneal@827: if results: bgneal@827: return HttpResponse(results, content_type='application/json') bgneal@827: bgneal@827: # Generate results bgneal@827: qs = BandEntry.objects.filter(is_approved=True) bgneal@827: if show_param == 'active': bgneal@827: qs = qs.filter(is_active=True) bgneal@827: elif show_param == 'inactive': bgneal@827: qs = qs.filter(is_active=False) bgneal@827: bgneal@827: bands = [] bgneal@827: for band in qs.iterator(): bgneal@831: note = render_to_string('bandmap/balloon.html', {'band': band}) bgneal@831: note = note.strip().replace('\n', '') bgneal@827: bands.append({ bgneal@827: 'name': band.name, bgneal@827: 'lat': band.lat, bgneal@827: 'lon': band.lon, bgneal@830: 'is_active': band.is_active, bgneal@831: 'note': note, bgneal@827: }) bgneal@827: results = json.dumps(bands) bgneal@827: bgneal@827: # Store in cache bgneal@827: cache.set(cache_key, results, 300) bgneal@827: bgneal@827: return HttpResponse(results, content_type='application/json')