django template render dict
# views.py
from django.shortcuts import render
def my_view(request):
my_dict = {'key1': 'value1', 'key2': 'value2'}
return render(request, 'my_template.html', {'my_dict': my_dict})
<!-- my_template.html -->
<!DOCTYPE html>
<html>
<head>
<title>My Template</title>
</head>
<body>
<h1>Values from the Dictionary:</h1>
<ul>
<li>{{ my_dict.key1 }}</li>
<li>{{ my_dict.key2 }}</li>
</ul>
</body>
</html>
In the
views.py
file, import therender
function fromdjango.shortcuts
.Define a view function (
my_view
) that takes arequest
parameter.Create a dictionary (
my_dict
) with key-value pairs.Use the
render
function to render themy_template.html
template. Pass therequest
object, the template name, and a dictionary containing the data to be rendered in the template.In the
my_template.html
file, define an HTML document.Use the
{{ my_dict.key1 }}
template tag to access and display the value associated with the key 'key1' in themy_dict
dictionary.Similarly, use the
{{ my_dict.key2 }}
template tag to access and display the value associated with the key 'key2' in themy_dict
dictionary.The rendered HTML will display a heading and an unordered list with the values from the dictionary.