템플릿에 정보 채우기
이전 강의 - 템플릿으로 html 불러오기에서는 후보에 대한 정보를 정적으로 보여줬습니다.
이 강의에서는 DB에 있는 정보를 html html로 전달해 후보에 대한 정보를 동적으로 보이는 방법을 설명합니다.
1. views.py에서 DB에 있는 후보 정보를 html에 전달
# C\Code\mysite\elections\views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Candidate
def index(request):
candidates = Candidate.objects.all()
context = {'candidates' : candidates} #context에 모든 후보에 대한 정보를 저장
return render(request, 'elections/index.html', context) # context로 html에 모든 후보에 대한 정보를 전달
2. index.html에서는 반복문을 돌며 전달받은 후보 정보를 보여줍니다
<!-- C\Code\mysite\elections\template\elections\index.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">
<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.area }} </td>
<td>기호 {{ candidate.party_number }} 번</td>
</tr>
{% endfor %}
<!-- 여기까지 -->
<tbody>
</table>
</body>
-
별거 아니긴 한대..
웅웅이
2019.5.7 13:32
0
-
궁금한 점이 하나 있습니다.
-
2018.5.12 14:43
2
-
sqlite 에서 새로 입력된 데이터에서 빠진 항목들
-
2017.11.6 00:50
1
-
sqlite 에서 새로 입력된 데이터에서 빠진 항목들
-
2017.11.6 00:50
1
-
출력이 되지 않습니다..
김수정
2017.5.18 16:41
3
-
{% %} 질문입니다.
-
2017.4.6 10:39
1
-
index.html에서 <tbody>의 닫는 태그가 <tbody>로 되어 있습니다.
조민철
2016.10.1 18:21
1
-
2. indedx.html에서는 반복문을 돌며 전달받은 후보 정보를 보여줍니다 <-오...
-
2016.6.30 21:11
1
-
화면에 출력이 안되네요
-
2016.5.27 20:48
2
-
궁금한게 있습니다
-
2016.5.13 21:11
1
-
강의노트 오타있습니다.
-
2016.3.25 12:17
1