views.py
# 데이터 베이스와 유사한 리스트 선언
blog_list = [
{
"id": 1,
"title": "장고는 너무 재미있어!!!",
"content": "This is the content of blog 1",
"author": "Author 1",
},
{
"id": 2,
"title": "파이썬도 너무 재미있어!!!!",
"content": "This is the content of blog 2",
"author": "Author 2",
},
{
"id": 3,
"title": "자바스크립트는 별로였어!!!",
"content": "This is the content of blog 3",
"author": "Author 3",
},
]
user_list = [
{
"id": 1,
"username": "hojun",
"email": "hojun@gmail.com",
"password": "1234",
},
{
"id": 2,
"username": "jihun",
"email": "jihun@gmail.com",
"password": "1234",
},
{
"id": 3,
"username": "junho",
"email": "junho@gmail.com",
"password": "1234",
},
]
def index(request):
return render(request, "main/index.html")
def bloglist(request):
context = {"blogitems": blog_list}
return render(request, "main/bloglist.html", context)
def blogdetails(request, pk):
blog = blog_list[pk - 1]
language = ["html", "css", "js", "python"]
context = {"blog": blog, "language": language}
return render(request, "main/blogdetails.html", context)
def userdetails(request, user):
finduser = None
for i in user_list:
if i["username"] == user:
finduser = i
if finduser is None:
return render(request, "main/notfound.html")
return render(request, "main/userdetails.html", {"user": finduser})
# index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
</head>
<body>
<h1>환영합니다!</h1>
</body>
</html>
# bloglist.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>bloglist</title>
</head>
<body>
<h1>bloglist 페이지 입니다.</h1>
<ul>
{# 주석 입니다! #}
{% for i in blogitems %}
<li><a href="/blog/{{ i.id }}">{{ i.title }} {{ i.id }}번째 게시물이야!!</a></li>
{% endfor %}
</ul>
</body>
</html>
위 코드에서 중괄호({}) 2개는 변수를 뜻한다. 중괄호와 %를 같이 쓰면 문법을 대입할 수 있다. {% if value %}
for문을 쓰는 경우에는 해당 태그가 끝나는 시점에 {% endfor %}
를 적어두자.
# blogdetails.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>blogdetails</title>
</head>
<body>
<h1>blogdetails</h1>
<h2>{{ blog.title }}</h2>
<p>{{ blog.author }}</p>
<p>{{ blog.content }}</p>
<p>{{ language }}</p>
<p>{{ language.0 }}</p>
{% for i in language %}
<p>이건 {{ i }}야!!!!</p>
{% endfor %}
</body>
</html>
.
으로 딕셔너리의 원소에 접근하는 법은 똑같다.
# userdetails.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>userinfo</title>
</head>
<body>
<h1>userinfo 페이지</h1>
<p>{{user.username}}</p>
<p>{{user.email}}</p>
</body>
</html>