模板继承不起作用 - Django 教程

Template Inheritance Does Not Work - Django Tutorial

我正在关注 Corey Schafer' Django tutorial. I have reached where I have to create a base.html template inheritance. After adjusting everything according to my project and running the server, my webpage presents itself as a source code in html format. click to see the page after server run。

我的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。

非常感谢您的帮助。

你应该这样做:

    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/