TechTogetWorld


 daviduino.co.kr

techtogetworld.com

 david201207.blog.me

cafe.naver.com/3dpservicedavid


투표관련 웹 "vote" Django WEB을 통해 장고의 기능을 확인해 가는 과정입니다.

글의 순서는 아래와 같습니다.


===========================================================================

1. 투표결과 나타내기

2. 투표기간 동적으로 표현하기

3. 지지율 동적으로 표현하기

4. 참고자료

===========================================================================



[ 투표결과 나타내기]


1. 투표결과 표현형  templates 만들기

    <!--C:\Code\mysite\elections\templates\elections\result.html -->

<!DOCTYPE html>

<html lang="en">

<head>

  <title>지역구 여론조사 결과</title>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

</head>

<body>

<div class="container">

<h1>지역구</h1>

<br>

<table class="table table-striped">

    <thead>

    <tr>

        <td><B>기간</B></td>

        <td><B>후보1</B></td>

        <td><B>후보2</B></td>        

    </tr>

    </thead>

    <tbody>

    <tr>

        <td> 기간1 </td>

        <td> 후보1 지지율</td>

        <td> 후보2 지지율</td>

    </tr>    

    <tbody>

</table>

</div>

</body>



2. URL을 투표결과로 연결하기

# C:\Code\mysite\elections\urls.py

from django.conf.urls import url

from . import views


urlpatterns = [

    url(r'^$', views.index),

    url(r'^areas/(?P<area>[가-힣]+)/$', views.areas), 

    url(r'^areas/(?P<area>[가-힣]+)/results$', views.results), 

    url(r'^polls/(?P<poll_id>\d+)/$', views.polls),

]


3. 투표후 투표결과 result위치값을 을 리턴하기/투표결과 함수를 정의하기

# C:\Code\mysite\elections\views.py


# 기존 import 유지

from django.http import HttpResponseRedirect


# def index(request) 유지


def polls(request, area):

    #...

    #return HttpResponse("finish") #여기 지우고

    return HttpResponseRedirect("/areas/{}/results".format(poll.area))



def results(request, area):

    return render(request, 'elections/result.html', )



[ 투표기간 동적으로 표현하기]


1. view.py 수정


 C:\Code\mysite\elections\views.py


def results(request, area):

    candidates = Candidate.objects.filter(area = area)

    polls = Poll.objects.filter(area = area)

    poll_results = []

    for poll in polls:

        result = {}

        result['start_date'] = poll.start_date

        result['end_date'] = poll.end_date


        poll_results.append(result)


    context = {'candidates':candidates, 'area':area,

    'poll_results' : poll_results}

    return render(request, 'elections/result.html', context)



2. view.py 수정

<html lang="en">

<head>

  <title>{{area}} 여론조사 결과</title>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

</head>

<body>

<div class="container">

<h1>{{area}}</h1>

<br>

<table class="table table-striped">

    <thead>

    <tr>

        <td><B>기간</B></td>

        {% for candidate in candidates %}

        <td><B>{{candidate.name}}</B></td>

        {% endfor %}

    </tr>

    </thead>

    <tbody>

    {% for result in poll_results %}

    <tr>

        <td> {{result.start_date.year}}/{{result.start_date.month}}/{{result.start_date.day}}~{{result.end_date.year}}/{{result.end_date.month}}/{{result.end_date.day}} </td>

        <td> 후보1 지지율</td>

        <td> 후보2 지지율</td>

    </tr>

    {% endfor %}

    <tbody>

</table>

</div>

</body>



[ 지지율 동적으로 표현하기]


1.views.py 수정


# C:\Code\mysite\elections\views.py

# 여론조사 결과보기2에 Contact모델과 이어지는 views.py


def results(request, area):

    candidates = Candidate.objects.filter(area = area)

    polls = Poll.objects.filter(area = area)

    poll_results = []

    for poll in polls:

        result = {}

        result['start_date'] = poll.start_date

        result['end_date'] = poll.end_date


        # poll.id에 해당하는 전체 투표수

        total_votes = Choice.objects.filter(poll_id = poll.id).aggregate(Sum('votes'))

        result['total_votes'] = total_votes['votes__sum']


        rates = [] #지지율

        for candidate in candidates:

            # choice가 하나도 없는 경우 - 예외처리로 0을 append

            try:

                choice = Choice.objects.get(poll = poll, candidate = candidate)

                rates.append(

                    round(choice.votes * 100 / result['total_votes'], 1)

                    )

            except :

                rates.append(0)

        result['rates'] = rates

        poll_results.append(result)


    context = {'candidates':candidates, 'area':area,

    'poll_results' : poll_results}

    return render(request, 'elections/result.html', context)


2.result.html 수정

<!-- C:\Code\mysite\elections\templates\elections\result.html -->

<!DOCTYPE html>

<html lang="en">

<head>

  <title>{{area}} 여론조사 결과</title>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

</head>

<body>

<div class="container">

<h1>{{area}}</h1>

<br>

<table class="table table-striped">

    <thead>

    <tr>

        <td><B>기간</B></td>

        {% for candidate in candidates %}

        <td><B>{{candidate.name}}</B></td>

        {% endfor %}

    </tr>

    </thead>

    <tbody>

    {% for result in poll_results %}

    <tr>

        <td> {{result.start_date.year}}/{{result.start_date.month}}/{{result.start_date.day}}~{{result.end_date.year}}/{{result.end_date.month}}/{{result.end_date.day}} </td>

        {% for rate in result.rates %}

        <td> {{rate}}%</td>

        {% endfor %}

    </tr>    

    <tbody>

    {% endfor %}

</table>

</div>

</body>




[ 참고자료]