from django.contrib.auth.decorators import login_required from django.db.models import Count from django.http import JsonResponse from django.shortcuts import render # Create your views here. from django.utils.decorators import method_decorator from django.views.generic import ListView from policy.models import DroughtSpi @method_decorator(login_required, name='dispatch') class DroughtSpiListView(ListView): context_object_name = 'spis' paginate_by = 100 def get_queryset(self): self.keyword = self.request.GET.get('keyword', '') if len(self.keyword) != 0: return DroughtSpi.objects.filter(code__contains=self.keyword) return DroughtSpi.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['keyword'] = self.keyword return context @login_required def drought_spi_chart(request): code = request.GET.get('code', 'V7001') year_from = request.GET.get('year_from', '1979') year_to = request.GET.get('year_to', '1989') codes = DroughtSpi.objects.only('code').values('code').annotate(total=Count('code')).order_by('code') years = range(1979, 2018) months = range(1, 13) spis = DroughtSpi.objects.filter(code=code, year__range=(year_from, year_to)) return render(request, 'policy/drought_spi_chart.html', {'codes': codes, 'years': years, 'months': months, 'spis': spis, 'code': code, 'year_from': year_from, 'year_to': year_to, }) @login_required def timeline4(request): return render(request, 'graphic/timeline4.html') @login_required def timeline5(request): return render(request, 'graphic/timeline5.html') @login_required def drought_spi_json(request): code = request.GET.get('code') year_from = request.GET.get('year_from') year_to = request.GET.get('year_to') year = request.GET.get('year') month = request.GET.get('month') q = DroughtSpi.objects.all() if code: q = q.filter(code=code) if year_from and year_to: q = q.filter(year__range=(year_from, year_to)) if year and month: q = q.filter(year=year, month=month) results = [] for spi in q: o = dict() o['code'] = spi.code o['year'] = str(spi.year) o['month'] = str(spi.month) o['value'] = spi.value results.append(o) return JsonResponse(results, safe=False)