brunch
매거진 백엔드

Django : views -> templates

딕셔너리, 리스트로 각각 전달

by 내가 사는 세상

{딕셔너리}로 전달

# views.py

from django.shortcuts import render

def my_view(request):

# 데이터를 포함한 dictionary 생성

datas_dict = {

'name': 'John',

'age': 30,

'city': 'New York'

}

# 템플릿에 데이터 전달

context = {

'datas_dict': datas_dict

}

return render(request, 'my_template.html', context)



<!-- my_template.html -->

<!DOCTYPE html>

<html>

<head>

<title>My Template</title>

</head>

<body>

{% for key_name, value_name in datas_dict.items %}

<p>{{ key_name }}: {{ value_name }}</p>

{% endfor %}

</body>

</html>



출력결과

<p>name: John</p>

<p>age: 30</p>

<p>city: New York</p>




[리스트]로 전달

# views.py

from django.shortcuts import render

def my_view(request):

# 데이터를 포함한 리스트 생성

datas_list = [

{'name': 'John', 'age': 30, 'city': 'New York'},

{'name': 'Alice', 'age': 25, 'city': 'Los Angeles'},

{'name': 'Bob', 'age': 35, 'city': 'Chicago'}

]

# 템플릿에 데이터 전달

context = {

'datas_list': datas_list

}

return render(request, 'my_template.html', context)



<!-- my_template.html -->

<!DOCTYPE html>

<html>

<head>

<title>My Template</title>

</head>

<body>

{% for data in datas_list %}

<p>Name: {{ data.name }}</p>

<p>Age: {{ data.age }}</p>

<p>City: {{ data.city }}</p>

{% endfor %}

</body>

</html>

keyword
매거진의 이전글Django - Model : 마이그레이션