본문 바로가기

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

[Django] 장고. http redirect하기

1. 시작하기 전에

바로전 글에서 했던 기능입니다.

여기서 선택을 누르면




'

이렇게 votes가 1 올라가면서 해당 페이지로 넘어가게 되는데 이 페이지를 redirect해서 결과화면이 나오는 페이지로 바꿔보겠습니다.




2. 화면을 그려줄 html파일을 만들자

mysite -> elections -> templates -> elections -> result.html파일을 만들어 아래 코드를 붙여넣어 줍니다.

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
<!DOCTYPE html>
<html lang="en">
<head>
  <title>{{candidate.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>지역구</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>
cs


3. urls.py에서 어떤화면에서 이 html을 나타내줄지 설정

어떤 화면에서 result.html을 나타내 줄것인지 설정해주기 위해 urls.py로 왔습니다.

파란색 원인 [가-힣]+는 뒤에 모든 한글을 허용한다는 뜻입니다.

즉. areas/한글만/results 라는 뜻이 되겠죠

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'^areas/(?P<area>[가-힣]+)/results$', views.results), 
    url(r'^polls/(?P<poll_id>\d+)/$', views.polls),
]
cs



4. views.py

HttpResponseRedirect를 사용하기 위하여 import를 추가시켜줍니다.

기존에 있던 HttpResponse를 Ridirect해주기 위해 코드를 바꿔줍니다.

그리고 사용해줬던 results함수를 추가해줍니다.

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
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
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")
    return HttpResponseRedirect("/areas/{}/results".format(poll.area))
 
def results(request, area):
    return render(request, 'elections/result.html')
cs



5. 결과확인

투표를 해봅니다




아직은 데이터를 넘겨주지 않았고, 지지율을 그려주는 설정도 안했기 때문에 그렇습니다. 조만간 지지율도 화면에 표시해보겠습니다.



6. 정리

1. 사용자의 후보선택을 POST request해서 HttpResponseRedirect로 넘겨줍니다

2. /areas/{}/result의 경로를 urls.py에서 정의를 하는데


1. areas/모든한글/results로 요청이 들어오면 views파일 안에 results라는 함수가 작동을 하는데

2. views파일로 들어가보면


results라는 함수를 보면 elections안에 result.html파일을 반환하라는 내용이 들어있습니다.


결국은 results로 들어오면 result.html파일을 열어달라는 뜻이네요





강의출처: http://tryhelloworld.co.kr/