본문 바로가기
개발

[Django] lotto - views와 템플릿 연동

by 마스터누누 2017. 6. 28.
728x90
반응형

lotto - views와 템플릿 연동




1
2
3
4
from django.shortcuts import render
 
def index(request):
    return render(request, "lotto/default.html", {"lottos":lottos})
cs


모델과 뷰를 완료했고 이제 템플릿만 남았다.

우선 views를 수정해보도록한다.


HttpResponse를 사용하고 있었는데 실제로는 이와 같이 사용하지 않는다.

템플릿과 뷰를 연동하기 위해서는 이것 대신에 render함수를 사용한다.

render 함수를 사용하기 위해서는 from django.shortcuts import render를 적용해야한다.


render 함수는 첫번째 인자로 request를 받는다.

이 request는 index로 들어온 바로 그 인자인다.

두번째는 랜더링 할 템플릿을, 마지막으로는 이 템플릿에 보내줄 객체를 넣어준다.

현재는 보내줄 값이 없으므로 {}를 보내도록 한다.


이 상태까지 완료하고 웹서버로 들어가면 아마 에러가 발생할 것이다.

왜냐하면 아직 템플릿이 만들어지지 않았기 때문이다.





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html lang="ko">
<head>
  <title>My Little Lotto</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
  <link href="//fonts.googleapis.com/css?family=Space+Mono" rel="stylesheet">
</head>
 
<body>
  <div class="page-header">
  <h1>My Lotto Page</h1>
  </div>
  <div class="container lotto">
    <h2>당첨 기원 (2)</h2>
    <p> last update:2000/1/1</p>
    <p> 1, 10, 15, 20, 30 </p>
  </div>
</body>
</html>
cs


템플릿을 사용하기 위해서는 lotto 폴더 내에 templates라는 폴더를 만들어야한다.

그리고 이 templates 폴더 내에 다시 lotto를 만든 후 default.html 파일을 만든다.

이렇게 구성하는 이유는 장고 프로젝트에 여러 앱을 등록하는데있어서 중복되지 않게 하기 위함이다.


다시 말해, lotto/templates/lotto/default.html 안에 위의 코드를 넣어주도록하자

default는 일반적인 html 파일이다.





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.page-header {
    background-color: #652596;
    margin-top: 0;
    padding: 20px 20px 20px 40px;
    font-family: 'Space Mono', monospace;
}
.page-header h1 {
  color: #FFFFFF;
}
.container {
  font-family: 'Space Mono', monospace;
}
.container h2 {
  color: #b9f442;
}
cs


템플릿까지 연동했지만, 아직 모양이 예쁘지 않다.

정적파일을 추가해서 디자인 적인 요소를 넣어주면 좀 더 보기가 좋을 것 같다.

정적파일은 이전에 settings.py에 STATIC_ROOT = os.path.join(BASE_DIR, 'static')으로 지정했었다.


위의 세팅은 경로를 지정한 것으로써 static 폴더 내에서 정적 파일을 관리한다는 뜻이다.

따라서 lotto 안에 static폴더를 생성하고, 다시 그안에 css폴더를 만들고 lotto.css를 넣어준다.

코드는 위와 같다.




1
2
{% load staticfiles %}
<link rel=”stylesheet” href=”{% static ‘css/lotto.css’ %}”>
cs


이렇게 만들어진 정적 파일을 추가하기 위해서 CSS가 적용될 HTML 상단에

{% load staticfiles %} 키워드를 적고

<link rel="stylesheet" href="{%static 'css/lotto.css'%}">를 추가해준다.


다음으로 장고에게 정적 파일이 추가 됨을 알려야한다.

이를 위해서 터미널에 $ python manage.py collectstatic이라는 명령어를 입력하도록한다.



출처 : 인프런, 파이썬 웹 프로그래밍, Django로 웹 서비스 개발하기



반응형

댓글