Example #1
0
def graph_climate(request):
    # DataSource object
    queryset = Climate.objects.raw("SELECT * FROM store_climate \
                                   where year>1000 \
                                   and year<9999  \
                                   group by season,region \
                                   order by season,region")

    #    data_source = ModelDataSource(queryset, fields= ['season', 'tmax', 'tmin', ] )
    data_source_tmin = ModelDataSource(queryset, fields=['season', 'tmin'])
    data_source_tmax = ModelDataSource(queryset, fields=['season', 'tmax'])
    data_source_tmean = ModelDataSource(queryset, fields=['season', 'tmean'])
    data_source_rainfall = ModelDataSource(queryset,
                                           fields=['season', 'rainfall'])
    data_source_sunshine = ModelDataSource(queryset,
                                           fields=['season', 'sunshine'])

    # Chart object

    chart_tmin = ColumnChart(
        data_source_tmin,
        options={
            'title': 'Min. Temperature (England,Scotland,UK,Wales - 1911-2017)'
        })
    chart_tmax = ColumnChart(
        data_source_tmax,
        options={
            'title': 'Max. Temperature (England,Scotland,UK,Wales - 1911-2017)'
        })
    chart_tmean = ColumnChart(
        data_source_tmean,
        options={
            'title': 'Mean Temperature (England,Scotland,UK,Wales - 1911-2017)'
        })
    chart_rainfall = ColumnChart(
        data_source_rainfall,
        options={'title': 'Rainfall (England,Scotland,UK,Wales - 1911-2017)'})
    chart_sunshine = ColumnChart(
        data_source_sunshine,
        options={'title': 'Sunshine (England,Scotland,UK,Wales - 1911-2017)'})

    context = {
        'chart_tmin': chart_tmin,
        'chart_tmax': chart_tmax,
        'chart_tmean': chart_tmean,
        'chart_rainfall': chart_rainfall,
        'chart_sunshine': chart_sunshine
    }

    template = loader.get_template('metoffice/graphs_climate.html')

    return HttpResponse(template.render(context, request))
Example #2
0
def results(request):
    charts = []

    for question in Question.objects.all():
        data = []
        data.append(['answer', 'votes'])
        for answer in question.answer_set.all():
            list_tmp = []
            list_tmp.append(answer.answer_txt)
            list_tmp.append(answer.answer_votes)
            data.append(list_tmp)
        charts.append(
            ColumnChart(SimpleDataSource(data=data),
                        options={
                            'title': str(question.question_txt),
                            'legend': {
                                'position': 'bottom'
                            },
                            'titleTextStyle': {
                                'color': 'black',
                                'fontSize': 22
                            },
                            'colors': ['#ff9400']
                        }))

    context = {
        'questions': Question.objects.all(),
        'title': 'Survey Results',
        'survey': Survey.objects.first(),
        'charts': charts,
    }

    return render(request, 'survey/results.html', context)
Example #3
0
def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    choices = list(question.choice_set.all())

    data = [['Choice', 'Votes']]
    for choice in choices:
        data.append([choice.choice_text, choice.votes])
    data_source = SimpleDataSource(data=data)

    chart = ColumnChart(data_source)
    context = {'question': question, 'chart': chart}
    return render(request, 'survey/results.html', context)
Example #4
0
def draw(request):

    queryset = Location.objects.filter(user__pk=request.user.id)
    data_source = ModelDataSource(queryset, fields=['place', 'population'])

    if request.method == 'GET' and not 'charts' in request.GET:
        chart = BarChart(data_source)
    elif request.GET['charts'] == "BarChart":
        chart = BarChart(data_source)
    elif request.GET['charts'] == "LineChart":
        chart = LineChart(data_source)
    elif request.GET['charts'] == "PieChart":
        chart = PieChart(data_source)
    elif request.GET['charts'] == "ColumnChart":
        chart = ColumnChart(data_source)

    context = {'chart': chart}
    return render(request, 'my_charts/draw.html', context)
Example #5
0
def student_graph(request, student_id):
    if not 'user_id' in request.session:
        messages.error(request, 'Must be logged in to continue!')
        return redirect('users:index')

    if request.method == 'POST':
        assign_id = request.POST.getlist('assignment')
        response_from_model = Grade.objects.find_assigns(
            request.POST, assign_id, student_id)

        data_source = SimpleDataSource(data=response_from_model)
        student = Student.objects.get(id=student_id)
        # Chart object
        chart = ColumnChart(
            data_source,
            options={'title': student.first_name + "'s" + ' Grade Report'})
        context = {'chart': chart, 'student': student}
    return render(request, 'grades/student_graph.html', context)
def workloadc(request):
    data = WorkloadC.objects.all()

    # DataSource object
    data_source = ModelDataSource(data, ['exp', 'avgReadLatency', 'avgThroughput'])

    classicOptions = {
        'series': {
            0: {'targetAxisIndex': 0},
            1: {'targetAxisIndex': 1}
            },
        'title': 'Workload C - Average latency on the left, Average throughput on the right',
        'vAxes': {
            0: {'title': 'AVG LATENCY'},
            1: {'title': 'AVG THROUGHPUT'}
            }
        }
    
    # Chart object
    chart = ColumnChart(data_source, options=classicOptions)
    context = {'chart': chart}
    return render(request, 'workloadc.html', context)
Example #7
0
def graph_weather(request):

    # Original DataSource object
    # queryset = Climate.objects.filter( region = 'UK',year__gt=1000, year__lt=9999, )
    # queryset = queryset.exclude(season__in=['SUM', 'WIN', 'AUT','ANN', 'SPR'])

    queryset = Weather.objects.raw("SELECT * FROM store_weather \
                                   where year>1000 \
                                   and year<9999  \
                                   and value <9999 \
                                   and attribute = 'tmin' \
                                   order by region, year, season")

    #    data_source = ModelDataSource(queryset, fields= ['season', 'tmax', 'tmin', ] )
    data_source = ModelDataSource(queryset, fields=['season', 'value'])

    # Chart object
    chart = ColumnChart(data_source,
                        options={'title': 'Temperature (Min - 1911-2017)'})

    context = {'chart': chart}
    template = loader.get_template('metoffice/graphs_weather.html')

    return HttpResponse(template.render(context, request))
Example #8
0
def stats(request):
    if request.method == 'POST':
        form_bat = SelectionForm_Battery(request.POST)
        form_snp = SelectionForm_SNP(request.POST)
        if form_bat.is_valid() and form_snp.is_valid():

            subjects = Subject.objects.all()

            #### must only be one var / field - need to check for / change this!!!
            field_bat = form_bat.cleaned_data['battery_selections'][0]
            var_bat = BatteryVariable.objects.get(var_name=field_bat)
            # val_objs_bat=[s.batval.get(variable=var_bat) for s in subjects] ######
            # vals_bat=[v.value for v in val_objs_bat]

            #### must only be one var / field - need to check for / change this!!!
            field_snp = form_snp.cleaned_data['rsIDs'][0]
            snp = SNP.objects.get(rs_id=field_snp)
            alleles = [snp.a1 + snp.a1, snp.a1 + snp.a2, snp.a2 + snp.a2]

            pairs = []
            for s in subjects:
                if s.genotype.filter(SNP=snp).count() == 1:
                    g = s.genotype.get(SNP=snp)
                    if g.genotype == '0' or g.genotype == '1' or g.genotype == '2':  # not NA or missing
                        if s.batval.filter(variable=var_bat).count() == 1:
                            v = s.batval.get(variable=var_bat)
                            if v.value != None:
                                pairs.append([v.value, g.genotype])
            # geno_objs=[s.genotype.get(SNP=snp) for s in subjects] #### not sure why i have to use genotype rather than genotype_set here bc the opposite was what worked in the shelL!
            # genos=[g.genotype for g in geno_objs]

            # pairs=list(zip(vals_bat,genos))  #### might work without the list bit but this was easier to work with in the shell
            g_vals = []
            # gs=set(genos) #set([pairs[i][1] for i in range(0,len(pairs))]) # if use this need to double check order
            gs = ['0', '1', '2']  # do it in reverse bc using append
            graph_array = [['Genotype', field_bat]]  # for graphos
            # calculate average of batval for each geno
            counts = []
            for g in gs:
                cur_vals = [p[0] for p in pairs if p[1] == g]
                if len(cur_vals) == 0:
                    cur_avg = 0
                else:
                    cur_avg = sum(cur_vals) / Decimal(len(cur_vals))
                g_vals.append(cur_avg)
                graph_array.append([
                    alleles[int(g)], cur_avg
                ])  # for graphos # prob not best way to get alleles
                counts.append(len(cur_vals))

            # plotting with graphos
            chart = ColumnChart(SimpleDataSource(data=graph_array),
                                options={
                                    'title':
                                    field_bat + ' by ' + field_snp +
                                    ' genotype'
                                })

            # return render(request, 'selected_stats.html',{'field_bat':field_bat,'field_snp':field_snp,'val_by_g':val_by_g,'script':script,'div':div})
            return render(
                request, 'selected_stats.html', {
                    'field_bat': field_bat,
                    'field_snp': field_snp,
                    'counts': counts,
                    'alleles': alleles,
                    'chart': chart
                })

    else:
        form_bat = SelectionForm_Battery()
        form_snp = SelectionForm_SNP()

    return render(request, 'selection_stats.html', {
        'form_bat': form_bat,
        'form_snp': form_snp
    })
Example #9
0
def home(request):
    data = [
        ['Date', 'Users'],
        ['2018-09-22', 2],
        ['2018-09-23', 0],
        ['2018-09-24', 0],
        ['2018-09-25', 0],
        ['2018-09-26', 0],
        ['2018-09-27', 0],
        ['2018-09-28', 0],
        ['2018-09-29', 1],
    ]
    data2 = [
        ['Date', 'No.of Transactions'],
        ['22-09-22', 6],
        ['22-09-23', 0],
        ['22-09-24', 0],
        ['22-09-25', 1],
    ]
    data3 = [
        ['Date', 'Active Users'],
        ['22-09-22', 2],
        ['22-09-23', 0],
        ['22-09-24', 0],
        ['22-09-25', 1],
    ]
    tes = User.objects.count()
    tes99 = User.objects.all()
    tes1 = Transaction.objects.count()
    tes12 = Transaction.objects.all()
    tes123 = Transaction.objects.annotate(Sum('Amount'))
    tes2 = Transaction.objects.filter(Description__contains='Cashing').count()
    tes44 = Transaction.objects.filter(Description__contains='Cashing')
    tes3 = Transaction.objects.filter(Description__contains='Bill').count()
    tes32 = Transaction.objects.filter(Description__contains='Bill')
    tes4 = Transaction.objects.filter(Description__contains='Friend').count()
    tes45 = Transaction.objects.filter(Description__contains='Friend')
    tes5 = Transaction.objects.filter(Description__contains='Purchase').count()
    tes56 = Transaction.objects.filter(Description__contains='Purchase')
    data_source = SimpleDataSource(data=data)
    data_source2 = SimpleDataSource(data=data2)
    data_source3 = SimpleDataSource(data=data3)
    chart = ColumnChart(data_source)
    chart2 = ColumnChart(data_source2)
    chart3 = ColumnChart(data_source3)
    context = {
        'tes': tes,
        'tes123': tes123,
        'tes99': tes99,
        'chart2': chart2,
        'chart': chart,
        'chart3': chart3,
        'tes1': tes1,
        'tes2': tes2,
        'tes3': tes3,
        'tes4': tes4,
        'tes5': tes5,
        'tes32': tes32,
        'tes44': tes44,
        'tes45': tes45,
        'tes56': tes56,
        'tes12': tes12,
    }
    return render(request, 'pay/home.html', context)
Example #10
0
def empresa_visualizacion(request, pk):
    empresa = get_object_or_404(Empresa, pk=pk)
    empresa_pk = 0
    if request.user.is_authenticated:
        usuario = Usuario.objects.get(user=request.user.id)
        empresa_pk = usuario.id_empresa.pk
        consumosPorAño = []
        consumosPorAño = Consumo.objects.filter(
            id_empresa=pk).values('año').annotate(consumo=Sum('consumo'))
        datosChart1 = [['Año', 'Consumo total']]
        for consumo in consumosPorAño:
            datosChart1.append([consumo['año'], int(consumo['consumo'])])
        consumosPorActivo = []
        consumosPorActivo = Consumo.objects.filter(
            id_empresa=pk).values('id_activo').annotate(consumo=Sum('consumo'))
        datosChart2 = [['Activo', 'Consumo total']]
        for consumo in consumosPorActivo:
            nombreActivo = Activo.objects.filter(pk=consumo['id_activo'])
            datosChart2.append([str(nombreActivo[0]), int(consumo['consumo'])])

        consumosPorTipo = []
        consumosPorTipo = Consumo.objects.filter(
            id_empresa=pk).values('tipo').annotate(consumo=Sum('consumo'))
        datosChart3 = [['Tipo', 'Consumo total']]
        for consumo in consumosPorTipo:
            datosChart3.append([str(consumo['tipo']), int(consumo['consumo'])])

        # DataSource object
        data_source1 = SimpleDataSource(data=datosChart1)
        data_source2 = SimpleDataSource(data=datosChart2)
        data_source3 = SimpleDataSource(data=datosChart3)
        # Chart object
        chart1 = ColumnChart(data_source1,
                             options={'title': 'Consumo total por año'})
        chart2 = PieChart(data_source2,
                          options={'title': 'Consumo total por activo'})
        chart3 = PieChart(data_source3,
                          options={'title': 'Consumo total por tipo'})
        return render(
            request, 'empresa_visualizacion.html', {
                'empresa': empresa,
                'empresa_pk': empresa_pk,
                'titulo': 'Graficos',
                'chart1': chart1,
                'chart2': chart2,
                'chart3': chart3
            })

    else:
        consumosPorAño = []
        consumosPorAño = Consumo.objects.filter(
            id_empresa=pk).values('año').annotate(consumo=Sum('consumo'))
        datosChart1 = [['Año', 'Consumo total']]
        for consumo in consumosPorAño:
            datosChart1.append([consumo['año'], int(consumo['consumo'])])
        consumosPorActivo = []
        consumosPorActivo = Consumo.objects.filter(
            id_empresa=pk).values('id_activo').annotate(consumo=Sum('consumo'))
        datosChart2 = [['Activo', 'Consumo total']]
        for consumo in consumosPorActivo:
            nombreActivo = Activo.objects.filter(pk=consumo['id_activo'])
            datosChart2.append([str(nombreActivo[0]), int(consumo['consumo'])])

        consumosPorTipo = []
        consumosPorTipo = Consumo.objects.filter(
            id_empresa=pk).values('tipo').annotate(consumo=Sum('consumo'))
        datosChart3 = [['Tipo', 'Consumo total']]
        for consumo in consumosPorTipo:
            datosChart3.append([str(consumo['tipo']), int(consumo['consumo'])])

        # DataSource object
        data_source1 = SimpleDataSource(data=datosChart1)
        data_source2 = SimpleDataSource(data=datosChart2)
        data_source3 = SimpleDataSource(data=datosChart3)
        # Chart object
        chart1 = ColumnChart(data_source1,
                             options={'title': 'Consumo total por año'})
        chart2 = PieChart(data_source2,
                          options={'title': 'Consumo total por activo'})
        chart3 = PieChart(data_source3,
                          options={'title': 'Consumo total por tipo'})
        return render(
            request, 'empresa_visualizacion.html', {
                'empresa': empresa,
                'titulo': 'Graficos',
                'chart1': chart1,
                'chart2': chart2,
                'chart3': chart3
            })
Example #11
0
def personalReport(request, report_id, user_id):
    
    focusedUser = Profile.objects.get(user_id = user_id)
    
    focusedUserName= focusedUser.user.first_name + ' '+ focusedUser.user.last_name
    
    if report_id == '1':
        
        productresults = productResults.objects.filter(user_id_number=user_id, update_date__gte=datetime.date(2017, 5, 1), update_date__lte=datetime.date(2017, 8, 31)).order_by('question_number')
        
        programmingresults = programmingResults.objects.filter(user_id_number=user_id, update_date__gte=datetime.date(2017, 5, 1), update_date__lte=datetime.date(2017, 8, 31)).order_by('question_number')
    
    if productresults:
        
        data = [['Product Questions', 'Rating']]

        for productresult in productresults:
        
            productquestion = Question.objects.get(id = productresult.question_number)
        
            info = [productquestion.question_text, productresult.rating_number]

            data.append(info)

        # DataSource object
        data_source = SimpleDataSource(data=data)
        
        # Chart object
        chart = ColumnChart(data_source,width =400, options={'title': 'Rating of each Prodcut_Q', 'colors': ['#FECF30'],'legend': {'position':'bottom'}, 'bar': {'groupWidth': '55%'}, 'vAxis': {'viewWindow':{'max':'10','min':'0'}}})

    else:
    
        chart = "No graph avaliable at this time because of data unavaliable"

    #Programming part

    if programmingresults:

        data2 = [['Programming Questions', 'Rating']]

        for programmingresult in programmingresults:
            
            programmingquestion = ProgrammingQuestion.objects.get(id = programmingresult.question_number)
            
            info = [programmingquestion.programming_question_text, programmingresult.rating_number]
            
            data2.append(info)

        # DataSource object
        data_source = SimpleDataSource(data=data2)
        
        # Chart object
        chart2 = ColumnChart(data_source,width =400, options={'title': 'Rating of each Programming_Q', 'colors': ['#666868'],'legend': {'position':'bottom'}, 'bar': {'groupWidth': '55%'}, 'vAxis': {'viewWindow':{'max':'10','min':'0'}}})

    else:

        chart2 = "No graph avaliable at this time because of data unavaliable"

    context = {'chart': chart,
               'chart2': chart2,
               'focusedUserName' : focusedUserName}

    return render(request, 'manage/personalReport.html', context)
Example #12
0
def report(request, report_id):
    if report_id == '1':
        
        productresults = productResults.objects.filter(update_date__gte=datetime.date(2017, 5, 1), update_date__lte=datetime.date(2017, 8, 31))
        
        programmingresults = programmingResults.objects.filter(update_date__gte=datetime.date(2017, 5, 1), update_date__lte=datetime.date(2017, 8, 31))
        
        report_title = "Welcome to the Summary Report (from 5-1 to 8-31)"

    
    if report_id == '2':

        productresults = productResults.objects.filter(update_date__gte=datetime.date(2017, 9, 1), update_date__lte=datetime.date(2017, 12, 31))
    
        programmingresults = programmingResults.objects.filter(update_date__gte=datetime.date(2017, 9, 1), update_date__lte=datetime.date(2017, 12, 31))
    
        report_title = "Welcome to the Summary Report (from 9-1 to 12-31)"

    else:

        productresults = productResults.objects.all()
    
        programmingresults = programmingResults.objects.all()
    
    profiles = Profile.objects.all()

    product_list = Product.objects.order_by('-created_date')[:5]

    productquestions= Question.objects.all()
    
    programmingquestions= ProgrammingQuestion.objects.all()
    
    if not productresults:
        
        chart = "No graph avaliable at this time because of data unavaliable"
    
    else:
    
        data = [['Product Questions', 'Rating']]
        
        for productquestion in productquestions:
            
            outputs =  productresults.filter(question_number=productquestion.id)
            
            total = 0.00
            
            count = 0.00
        
            if outputs:
            
                for output in outputs:
                
                    total += output.rating_number
                
                    count += 1
                
                info = [productquestion.question_text, round(total/count,2)]

                data.append(info)

        # DataSource object
        data_source = SimpleDataSource(data=data)

        # Chart object
        chart = ColumnChart(data_source,width =500, options={'title': 'Average rating of each Prodcut_Q', 'legend': {'position':'right'}, 'bar': {'groupWidth': '55%'}, 'vAxis': {'viewWindow':{'max':'10','min':'0'}}})

    #get rating for each programming question

    if not programmingresults:

        chart2 = "No graph avaliable at this time because of data unavaliable"

    else:

        data2 = [['Programming Questions', 'Rating']]
        
        for programmingquestion in programmingquestions:
            
            outputs =  programmingresults.filter(question_number=programmingquestion.id)
            
            total = 0.00
            
            count = 0.00
            
            if outputs:
            
                for output in outputs:
                    
                    total += output.rating_number
                    
                    count += 1

                info2 = [programmingquestion.programming_question_text, round(total/count,2)]
            
            data2.append(info2)

        # DataSource object
        data_source2 = SimpleDataSource(data=data2)
        
        # Chart object
        chart2 = ColumnChart(data_source2,width =500, options={'title': 'Average rating of each Programming_Q', 'colors': ['green'], 'legend': {'position':'right'}, 'bar': {'groupWidth': '40%'}, 'vAxis': {'viewWindow':{'max':'10','min':'0'}}})


    context = {'profiles' : profiles,
        
        'productquestions': productquestions,
            
        'programmingquestions':programmingquestions,
                
        'productresults' : productresults,
                
        'programmingresults' : programmingresults,

        'report_title' : report_title,

        'product_list': product_list,

        'chart': chart,

        'chart2': chart2,

        'report_id' : report_id}
    
    return render(request, 'manage/report.html', context)
Example #13
0
def scenario_detail(request, pk=None):
    recent_pk = Scenario.objects.all().order_by("-date")[0].pk
    scenarios = Scenario.objects.all()
    if pk == None:
        pk = Scenario.objects.all().order_by("-date")[0].pk
    # scenario = get_object_or_404(Scenario.objects.prefetch_related('auctionyear_set__pot_set__technology_set', 'policies'), pk=pk)
    try:
        scenario = Scenario.objects.prefetch_related(
            'auctionyear_set__pot_set__technology_set',
            'policies').get(pk=pk)  #new
    except ObjectDoesNotExist:
        context = {
            'pk': pk,
            'type': 'scenario',
            'policies': Policy.objects.all(),
            'scenarios': scenarios,
            'recent_pk': recent_pk,
        }
        return render(request, '404.html', context)
    # print('instantiating a scenario object with prefetched attributes')
    # print(scenario.name)
    # print("[lease sss don't c a che me!")
    try:
        scenario.get_results()
        # intermediate_results = scenario.intermediate_results()
        e = None
    except ScenarioError as e:
        context = {
            'scenario': scenario,
            'policies': Policy.objects.all(),
            'scenarios': scenarios,
            'recent_pk': recent_pk,
            'error_message': e,
        }
        return render(request, 'lcf/scenario_error.html', context=context)
    else:
        # chart = {}
        # df = {}
        context = {
            'scenario': scenario,
            'policies': Policy.objects.all(),
            'scenarios': scenarios,
            'recent_pk': recent_pk,
        }
        for column in [
                'awarded_cap', 'awarded_gen', 'cum_owed_v_wp',
                'cum_owed_v_gas', 'cum_owed_v_absolute', 'cum_awarded_gen'
        ]:
            for num in [1, 2]:
                pivot_table = getattr(scenario, 'pivot')(column, num)
                context["".join([column, str(num)
                                 ])] = getattr(scenario,
                                               'pivot_to_html')(pivot_table)

        for column in ["awarded_cap", "cum_awarded_gen"]:
            chart_data, options, options_small = scenario.df_to_chart_data(
                column)['chart_data'], scenario.df_to_chart_data(
                    column)['options'], scenario.df_to_chart_data(
                        column)['options_small']
            data_source = SimpleDataSource(data=chart_data)
            context["".join([column, "_chart"])] = ColumnChart(data_source,
                                                               options=options)
            # context["".join([column,"_chart_small"])] = ColumnChart(data_source, options=options_small)

        for column in ["cum_owed_v_wp", "cum_awarded_gen"]:
            chart_data, options, options_small = scenario.df_to_chart_data(
                column, summary=True)['chart_data'], scenario.df_to_chart_data(
                    column,
                    summary=True)['options'], scenario.df_to_chart_data(
                        column, summary=True)['options_small']
            data_source = SimpleDataSource(data=chart_data)
            # if column == "cum_owed_v_wp":
            # options_small['vAxis']['viewWindowMode'] = 'explicit'
            # options_small['vAxis']['viewWindow'] = {'max': 3.2}
            # options_small['vAxis']['viewWindow']['min'] = 0
            # options_small['vAxis']['viewWindow']['max'] = 3.2
            context["".join([column, "_chart_small"
                             ])] = ColumnChart(data_source,
                                               options=options_small)

        print('rendering request')
        return render(request, 'lcf/scenario_detail.html', context)
Example #14
0
def chart_archive(request, chartfrom, year, month, day=0):
    """Funtion"""
    inyear = int(year)
    inmonth = int(month)
    inday = int(day)
    if inmonth > 0 and inmonth <= 12:
        now = timezone.now()
        if inday == 0:
            startdate = now.replace(year=inyear,
                                    month=inmonth,
                                    day=1,
                                    hour=0,
                                    minute=0,
                                    second=0,
                                    microsecond=0)
            enddate = startdate.replace(month=inmonth + 1)
        else:
            enddate = now.replace(year=inyear,
                                  month=inmonth,
                                  day=inday,
                                  hour=0,
                                  minute=0,
                                  second=0,
                                  microsecond=0) - timezone.timedelta(hours=9)
            startdate = enddate - timezone.timedelta(days=7)
            enddate = enddate - timezone.timedelta(microseconds=1)

        issues = Issue.objects.exclude(email__iexact='').filter(
            datetime__range=(startdate,
                             enddate)).order_by('count', 'goodcount')

        data_list = [['media', '좋아요', '나빠요']]

        for issue in issues:
            giza = Giza.objects.filter(email__iexact=issue.email)
            if giza:
                found = False
                for item in data_list:
                    if giza[0].belongto == item[0]:
                        item[1] += issue.goodcount
                        item[2] += issue.count
                        found = True
                        break
                if not found:
                    data_list.append(
                        [giza[0].belongto, issue.goodcount, issue.count])
                found = False

        data = sorted(data_list, key=get_key_2,
                      reverse=True)[0:settings.RANKING_LIST_LIMIT + 1]
        data_source = SimpleDataSource(data=data)
        chart_all_bad = ColumnChart(data_source)

        data = sorted(data_list, key=get_key_1,
                      reverse=True)[0:settings.RANKING_LIST_LIMIT + 1]
        data_source = SimpleDataSource(data=data)
        chart_all_good = ColumnChart(data_source)

        data = sorted(data_list, key=get_key_1, reverse=True)
        data_source = SimpleDataSource(data=data)
        chart_good = PieChart(data_source)

        data = sorted(data_list, key=get_key_2, reverse=True)
        data_copy = [x[:] for x in data]
        for l in data_copy:
            del l[1]
        data_source = SimpleDataSource(data=data_copy)
        chart_bad = PieChart(data_source)

        trend_data = [[
            'date', data_copy[1][0], data_copy[2][0], data_copy[3][0],
            data_copy[4][0], data_copy[5][0]
        ]]

        trend_start = startdate
        for i in range(7):
            trend_end = trend_start + timezone.timedelta(1)
            trend_issues = issues.filter(datetime__range=(trend_start,
                                                          trend_end)).order_by(
                                                              'count',
                                                              'goodcount')
            if i == 0:
                trend_data.append([trend_end.date(), 0, 0, 0, 0, 0])
            else:
                trend_data.append([
                    trend_end.date(), trend_data[i][1], trend_data[i][2],
                    trend_data[i][3], trend_data[i][4], trend_data[i][5]
                ])
            for trend_issue in trend_issues:
                giza = Giza.objects.filter(email__iexact=trend_issue.email)
                if giza:
                    for j in range(5):
                        if giza[0].belongto == trend_data[0][j + 1]:
                            trend_data[i + 1][j + 1] += trend_issue.count
            trend_start = trend_end

        data_source = SimpleDataSource(data=trend_data)
        chart_trend = LineChart(data_source)

        if inday == 0:
            msg = u'%s년 %s월 언론사 데이터입니다.' % (year, month)
        elif chartfrom == 'live':
            msg = u'실시간 업데이트되는 일주일간의 언론사 데이터입니다.'
        else:
            formatted_start = formats.date_format(
                startdate + timezone.timedelta(hours=9), "Y-m-d")
            formatted_end = formats.date_format(
                enddate + timezone.timedelta(hours=9), "Y-m-d")
            msg = u'%s ~ %s 사이의 언론사 데이터입니다.' % (formatted_start, formatted_end)

        return render(
            request, "issue/chart.html", {
                'chart_all_bad': chart_all_bad,
                'chart_all_good': chart_all_good,
                'chart_good': chart_good,
                'chart_bad': chart_bad,
                'chart_trend': chart_trend,
                'chartfrom': chartfrom,
                'msg': msg,
            })
    else:
        return HttpResponse(u"기간 설정 오류")