Как получить ключ и значения из словаря, чтобы отобразить их на странице Django?
Я хочу создать страницу, на которой каждый автор будет указывать свою цитату. Я пробовал, но все мои попытки не увенчались успехом. Проблемы возникают из-за приведенной ниже функции.
quotes = {
"Arthur Ashe": "Start where you are, Use what you have, Do what you can.",
"Steve Jobs": "Don’t watch the clock; do what it does. Keep going.",
"Sam Levenson": "Don’t watch the clock; do what it does. Keep going.",
" Robert Collier": "Success is the sum of small efforts, repeated day in and day out.",
"Nelson Mandela": "It always seems impossible until it’s done.",
"Mahatma Gandhi": "The future depends on what you do today.",
"Zig Ziglar": "You don’t have to be great to start, but you have to start to be great.",
"Dave": "Discipline is doing what needs to be done, even if you don’t want to do it.",
"Suzy Kassem": "Doubt kills more dreams than failure ever will.",
"Pablo Picasso": "Action is the foundational key to all success."
}
def mypage(request):
messages = [quotes[item] for item in quotes]
authors = [item for item in quotes]
return render(request, "quotes/mypage.html", {"authors": authors, "quotes":messages})
Вы можете передать весь словарь целиком:
def mypage(request):
messages = [quotes[item] for item in quotes]
authors = [item for item in quotes]
return render(request, 'quotes/mypage.html', {'quotes': quotes})
а затем в шаблоне выполните перечисление над .items()
из quotes
, таким образом:
{% for author, quote in quotes.items % }
{{author}} said: "{{ quote }}"
{% endfor % }