본문 바로가기

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

[Django] 장고. DB를 html화면에 출력하기

DB에 저장된 데이터들을 템플릿에 있는 html화면에 출력해 보겠습니다.



1. views.py에서 DB의 어린이 정보를 html에 전달

Views.py에서 수정합니다.

1. Candidate.objects.all(): Candidate의 모든 objects들을 불러와서 candidates라는 변수에 저장합니다.

2. candidates변수안에 정보들을 context에 저장합니다.

3. elections/index.html에 context의 정보들을 같이 전송합니다.

1
2
3
4
5
6
7
8
9
10
11
12
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로 전달
cs



2. index.html에서 데이터를 받고 출력

html에서 반복문을 사용하려면 {%%}안에 파이썬 코드를 넣어주면 실행이 됩니다.

그리고 반드시 끝나는 부분에 {%endfor%}를 넣어줘서 구분해 줍니다.

for문을 사용해주고 그 안에는 각각 전달받는 매개변수들을 출력할 수 있게 입력해줍니다.


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
<!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>{{candidate.area}}</td>
        </tr>
        {% endfor %}
        <tbody>
    </table>
</body>
cs




새로고침하면 반복문으로 저장된 데이터들이 계속해서 추가되는 모습




P.S 새로고침으로 안되는분들 or 서버를 열지 않은분들

powershell에서 경로를 mysite로 해주시고 서버를 열어주시면 됩니다.








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