본문 바로가기

파이썬 프로그래밍/Django기초

[Django] 장고. 버튼을 눌러 DB에 저장

1.area.html 화면디자인

1. poll에 데이터가 들어온다면 표를 실행합니다.

2. 아무 데이터가 없다면 해당 문자를 페이지에 출력합니다

3. 조건문이 시작했으면 마무리를 반드시 지어줍니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<!-- \mysite\templates\elections\area.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>
{% if poll %}
    <table class="table table-striped">
        <thead>
        <tr>
            <td><B>이름</B></td>
            <td><B>소개</B></td>
            <td><B>번호</B></td>
            <td><B>투표하기</B></td>
        </tr>
        </thead>
        <tbody>
        {% for candidate in candidates %}
        <tr>
            <td> {{ candidate.name }}</td>
            <td> {{ candidate.introduction }} </td>
            <td> 번호{{ candidate.party_number }}번 </td>
            <td>
                <form action = "/polls/{{poll.id}}/" method="post">
                <!--poll이라는 함수에 id값을 url경로를 포함하여 전달, 추후 urls.py와 views.py에서 처리해야함-->
                {% csrf_token %}
                <!--아무나 이와같은 포스트를 할 수 없도록 하고 해당 토큰을 가지고있는 클라이언트만 포스트 할 수 있도록 함-->
                    <button name="choice" value="{{candidate.id}}">선택</button>
                                        <!--선택한 후보의 id값 전달-->
                </form>
            </td>
        </tr>
        {% endfor %}
        </tbody>
    </table>
{% else %}
여론조사가 없습니다
{% endif %}
</div>
</body>
cs



2. urls를 통한 받아드릴 준비

urls.py

설명은 주석 참고. 한가지 붙이자면 <poll_id>\d+는 페이지를 poll_id로 하는데 정수형으로 받겠다는 뜻

1
2
3
4
5
6
7
8
9
from django.conf.urls import url
from . import views
 
urlpatterns = [
    url(r'^$', views.index),
    url(r'^areas/(?P<area>.+)/$', views.areas),
    url(r'^polls/(?P<poll_id>\d+)/$', views.polls)
    #이 url에 대한 요청을 views.polls가 처리하게 만듭니다.
]
cs




3. polls함수를 구현

views.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from django.shortcuts import render
from django.http import HttpResponse
 
from .models import Candidate, Poll, Choice
import datetime
 
# Create your views here.
def index(request):
    candidates = Candidate.objects.all()
    context = {'candidates':candidates}
        #context에 모든 어린이 정보를 저장
    return render(request, 'elections/index.html', context)
        #context안에 있는 어린이 정보를 index.html로 전달
 
def areas(request, area):
    today = datetime.datetime.now()
    try :
        poll = Poll.objects.get(area = area, start_date__lte = today, end_date__gte=today) # get에 인자로 조건을 전달해줍니다. 
        candidates = Candidate.objects.filter(area = area) # Candidate의 area와 매개변수 area가 같은 객체만 불러오기
    except:
        poll = None
        candidates = None
    context = {'candidates': candidates,
    'area' : area,
    'poll' : poll }
    return render(request, 'elections/area.html', context)
 
def polls(request, poll_id):
    poll = Poll.objects.get(pk = poll_id)#Poll객체를 구분하는 녀석은 poll_id이므로 PK지정
    selection = request.POST['choice']
 
    try:
        #choice모델을 불러와서 1을 증가시킨다 
        choice = Choice.objects.get(poll_id = poll.id, candidate_id = selection)
        choice.votes += 1
        choice.save()
    except:
        #최초로 투표하는 경우, DB에 저장된 Choice객체가 없기 때문에 Choice를 새로 생성합니다
        choice = Choice(poll_id = poll.id, candidate_id = selection, votes = 1)
        choice.save()
 
    return HttpResponse("finish")
cs



4. 저장을 확인하기 위한 admin 페이지에 추가

admin.py

admin에 Choice를 추가합니다

1
2
3
4
5
6
7
8
9
from django.contrib import admin
 
from . models import Candidate, Poll, Choice
# Register your models here.
 
 
admin.site.register(Candidate)
admin.site.register(Poll)
admin.site.register(Choice)
cs



5.결과확인

투표를 합니다.




그러면 이렇게 나옵니다.





admin페이지로 들어가면 추가해준 Choice가 나옵니다.




투표받은 후보가 한명이 있네요




카운트도 알맞게 올라간 것을 확인할 수 있습니다.