본문 바로가기

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

[Django] 장고. 템플릿을 통한 HTML을 불러오기(장고 템플릿 기초 이해하기)

본 게시글은 템플릿안에 있는 htm파일을 장고로 불러오는 방법과 템플릿이 무엇인지 구동원리를 이해하기 위한 기초 글입니다.

1. 기본 디렉토리 세팅

elections폴더 안에 templates폴더를 만들고 그안에 elections폴더를 또 만들고 그안에 index.html을 만들어줍니다.

왜 이렇게 복잡하게 하는가?

그이유는 장고가 템플릿을 찾는 방식때문에 그렇습니다.

그림을 통해 이해하겠습니다.

현재 왼쪽이 제가 구성한 디렉토리 화면입니다.

만약 elections app말고 다른 app에 templates에도 index.html이 온다면?

그렇다면 이름이 중복되어 꼬일수 있기 떄문에 elections app안에 templates안에 app이름으로 또 만들어 주는 것입니다.

만약 elections app 말고 join이라는 app을 만들게 된다면 index.html의 구조는 이렇게 됩니다.

join App -> templates -> join -> index.html



2. index.html 설정하기

index.html에 해당 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
<!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>
        <tr>
            <td>가후보</td>
            <td>후보입니다.</td>
            <td>도봉구</td>
            <td>1번</td>
        </tr>
        <tr>
            <td>나후보</td>
            <td>후보입니다.</td>
            <td>강남구</td>
            <td>2번</td>
        </tr>
        <tbody>
    </table>
</body>
cs


3. index.html파일을 장고와 연결하기

views.py로 들어옵니다.

1
2
3
4
5
6
7
8
from django.shortcuts import render
from django.http import HttpResponse
 
from .models import Candidate
 
# Create your views here.
def index(request):
    return render(request, 'elections/index.html')
cs
8번째줄만 보시면 됩니다.

render를 통해 request 받는데 그 경로는 elections(폴더)/index.html을 불러온다고 이해하시면 됩니다.



그리고 서버가 열려있다면 새로고침 해주시면 됩니다.





P.S 만약 서버가 안열려있다면?

powershell에서 서버를 열어줍니다.











본 게시글은 https://tryhelloworld.co.kr/ 강의를 바탕으로 정리한 게시글입니다.