0

我正在关注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。

非常感谢您的帮助。

4

1 回答 1

0

你应该这样做:

    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/

于 2021-10-24T14:54:12.103 回答