본문 바로가기

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

[Django] 장고. 화면구현(DB내용을 불러와 화면에 출력)


1. 링크만들기

elections -> index.html에 28, 29번째 줄을 수정합니다. a href = 링크를 넣어준다는 html코드로 클릭하면 areas라는 이름의 함수를 실행한다는 뜻입니다. 아래 코드 참고하여 수정하세요

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
<!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">
    <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.party_number}}번</td>
            <td>{{candidate.name}}</td>
            <td>{{candidate.introduction}}</td>
            <td><a href= "areas/{{candidate.area}}/">
            {{candidate.area}}</a></td>
        </tr>
        {% endfor %}
        <tbody>
    </table>
</body>
cs


elections -> urls.py에서 7번째 줄을 보시면 만들어줄 areas의 url을 설정해주는 코드입니다.

1
2
3
4
5
6
7
8
from django.conf.urls import url
from . import views
 
urlpatterns = [
    url(r'^$', views.index),
    url(r'^areas/(?P<area>.+)/$', views.areas)
            #특정 url에 대해서       views.areas가 실행되도록 합니다.
]
cs

views.areas라는 함수에 <area>를 넣어주고 싶을때 사용하며, <area>다음에 .+는 어떤 자료형을 허용할지 설정하는 코드입니다. .+의 경우 전부다 허용하여 \d를 해주면 숫자만 허용하게 됩니다.

즉 url을 어떤 형식으로 허용할지

이런 원리입니다. 페이지에 입력하면 그 입력한 값대로 나오네요


1.1. 확인

서버를 열어줍니다.




서울이라는 글자에 링크가 걸렸습니다.

클릭해봅니다.





클릭하면 링크에 접속이 되는것을 확인할 수 있습니다.







2. 반을 클릭하면 반정보가 나오게 하기

2.1.화면디자인

mysite -> elections -> templates -> elections -> area.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
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>반</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>소개</B></td>
            <td><B>번호</B></td>
            <td><B>투표하기</B></td>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td> 후보1</td>
            <td> 후보소개 </td>
            <td> 기호1번 </td>
            <td>
                <form action = "#" method="post">
                    <button name="choice" value="#">선택</button>
                </form>
            </td>
        </tr>
        <tr>
            <td> 후보2</td>
            <td> 후보소개 </td>
            <td> 기호2번 </td>
            <td>
                <form action = "#" method="post">
                    <button name="choice" value="#">선택</button>
                </form>
            </td>
        </tr>       
        </tbody>
    </table>
</div>
</body>
cs



2.2.디자인한 화면 url로 연결

elections -> views.py에 14,15번째줄을 추가합니다. 아래 코드 참고

1.에서 만들어준 area.html을 응답받기 위한 함수를 생성합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from django.shortcuts import render
from django.http import HttpResponse
 
from .models import Candidate
 
# 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):
    return render(request, 'elections/area.html')
cs




2.3. 확인

해바라기반을 클릭합니다.




areas.html 페이지가 잘 나오네요

지금은 화면만 불러온것입니다.

이제 화면에 해바라기반 친구들의 정보들을 불러와 보겠습니다



3.해바라기반 친구들 정보 불러오기

코드는 아래있으며 18번째줄 설명은 다음이미지에 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from django.shortcuts import render
from django.http import HttpResponse
 
from .models import Candidate
 
# 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):
    candidates = Candidate.objects.filter(area = area) #Candidate의 area와 매개변수 area가 같은 객체만 불러오기
    context = {'candidates': candidates,
    'area' : area}
    return render(request, 'elections/area.html', context)#그 정보는 area로 전달된다
cs

1. 빨간원 area는 매개변수로 받은 area, 파란원 area는 candidate 함수에서 넘어온 area. 두개가 같은 값만 filter해서 candidates에 값을 넣어준다

2. 1번에서 넘겨받은 값을 context에 넣어준다

3. area.html에 context값을 전달한다




반복문을 사용하여 후보들의 정보를 출력해줍니다. 아래 코드 참고

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
<!-- \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>
    <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 = "#" method="post">
                    <button name="choice" value="#">선택</button>
                </form>
            </td>
        </tr>
        {% endfor %}
        </tbody>
    </table>
</div>
</body>
cs



3.1. 결과확인

잘 바뀐것을 확인하실 수 있습니다.