【问题标题】:Template Inheritance Does Not Work - Django Tutorial模板继承不起作用 - Django 教程
【发布时间】:2021-12-10 07:06:00
【问题描述】:

我关注Corey Schafer' Django tutorial。我已经到了必须创建 base.html 模板继承的地方。根据我的项目调整所有内容并运行服务器后,我的网页以 html 格式的源代码呈现。 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。

非常感谢您的帮助。

【问题讨论】:

  • 您希望将标题添加到上下文中,但不是吗?你不能传递多个上下文字典,你需要将它们组合成一个
  • @IainShelvington 我将标题放在上下文字典中,它起作用了。谢谢!!

标签: python django inheritance django-templates django-inheritance


【解决方案1】:

你应该这样做:

    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-01-10
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 2011-12-31
    相关资源
    最近更新 更多