我正在關注Corey Schafer 的 Django 教程。我已經到了必須創建 base.html 模板繼承的地方。根據我的專案調整所有內容并運行服務器后,我的網頁將自己顯示為 html 格式的源代碼。服務器運行后點擊查看頁面。
我的 views.py 代碼:
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
# Create your views here.
def index(request):
text = "welcome to the website - python"
posts = [
{
'title': 'The Fault in Our Stars', 'price': '3.0 BD', 'post_date': '24-10-2021'
},
{
'title': 'The Black Swan', 'price': '3.5 BD', 'post_date': '23-10-2021'
},
{
'title': 'Watchmen', 'price': '5.0 BD', 'post_date': '22-10-2021'
}
]
context = {
'text': text, 'posts': posts
}
return render(request, 'blog/index.html', context, {'title': 'Bookish Bahrain - Home'})
我的 base.html 代碼:
<!DOCTYPE html>
<html lang="en">
<head>
{% if title %}
<title> {{ title }} </title>
{% else %}
<title> Bookish Bahrain </title>
{% endif %}
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
我的 index.html 代碼:
{% extends "blog/base.html" %}
{% block content %}
{% for post in posts %}
<p> {{post.title}} </p>
<p> {{post.price}} </p>
<p> {{post.post_date}} </p>
{% endfor %}
{% endblock content %}
我的 Django 版本是 3.9.7。
非常感謝您的幫助。
uj5u.com熱心網友回復:
你應該這樣做:
context = {
'text': text, 'posts': posts,
'title': 'Bookish Bahrain - Home'
}
return render(request,'blog/index.html', context )
簽出這個:https : //docs.djangoproject.com/en/3.2/topics/http/shortcuts/
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/339637.html
