drought_backup/policy/views.py

72 lines
2.4 KiB
Python
Raw Normal View History

2018-07-09 15:00:48 +00:00
from django.contrib.auth.decorators import login_required
2018-07-09 04:14:17 +00:00
from django.db.models import Count
2018-07-09 15:00:48 +00:00
from django.http import JsonResponse
2018-07-09 03:52:42 +00:00
from django.shortcuts import render
# Create your views here.
2018-07-09 15:00:48 +00:00
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
2018-12-13 12:50:33 +00:00
@login_required
2018-07-09 15:00:48 +00:00
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, })
2018-12-13 12:50:33 +00:00
@login_required
2018-07-09 15:00:48 +00:00
def timeline4(request):
return render(request, 'graphic/timeline4.html')
2018-07-09 04:14:17 +00:00
2018-12-14 06:54:10 +00:00
@login_required
def timeline5(request):
return render(request, 'graphic/timeline5.html')
2018-12-13 12:50:33 +00:00
@login_required
2018-07-09 15:00:48 +00:00
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)