Skip to main content
 首页 » 编程设计

python之Django 变量在标题部分不可见

2024年10月01日29pengyingh

我有一个博客的基本开端,它列出了从 header.html 扩展而来的 post_list.html 数据库中的博客文章。我也在尝试在 header 中获取一个变量作为口号,但这不起作用。

header.html - 这呈现没有从管理页面输入的“propaganda.slogan”并包含内容:

<!DOCTYPE html> 
  <html lang="en"> 
  <head> 
    <title>hey!</title> 
    <meta charset="utf-8" /> 
    {% load staticfiles %} 
    <link rel="stylesheet" href="{% static 'blog/css/bulma.css' %}"      type="text/css"/>  
  </head>     
  <body> 
    <section class="hero is-success is-bold"> 
        <div class="hero-body"> 
            <div class="container"> 
                {% block slogan %} 
                    <ul> 
                    {% for propaganda in propagandas %} 
                        <li>{{ propaganda.slogan }}</li> 
                    {% endfor %} 
                    </ul>        
                {% endblock %} 
                <h1 class="title"> 
                    My weblog 
                </h1> 
            </div> 
        </div> 
    </section> 
    {% block content %} 
    {% endblock %} 
</body> 
</html> 

post_list.html 扩展 header.html 并显示来自 models.py 的帖子列表:

{% extends "blog/header.html" %} 
{% block content %} 
    {% for post in posts %} 
        <section class="section"> 
            <div class="container"> 
                <h1 class="title"><a href="#">{{ post.title }}</a></h1> 
                <p>{{ post.summary|linebreaksbr }}</p> 
                <p>published: {{ post.last_edited }}</p> 
            </div> 
        </section> 
    {% endfor %}     
{% endblock %} 

models.py 看起来像这样:

from django.db import models 
from django.utils import timezone 
 
# Create your models here. 
class Propaganda(models.Model): 
    slogan = models.CharField(max_length=140, blank=True, null=True) 
 
    def __str__(self): 
        return self.slogan 
 
 
class Post(models.Model): 
    title = models.CharField(max_length=140, blank=False, null=False) 
    content = models.TextField() 
    summary = models.CharField(max_length=500) 
    created_date = models.DateTimeField() 
    last_edited = models.DateTimeField() 
 
    def __str__(self): 
        return self.title 

最后,views.py 是:

from django.shortcuts import render 
from .models import Post, Propaganda 
 
# Create your views here. 
def post_list(request): 
    posts = Post.objects.all() 
    return render(request, 'blog/post_list.html', {'posts': posts}) 
 
def header(request): 
    propagandas = Propaganda.objects.all() 
    return render(request, 'blog/header.html', {'propagandas': propagandas}) 

那么为什么我在post_list.html中可以得到帖子标题、摘要和日期的列表,但是在页眉中却无法得到宣传标语的列表?

对我来说,它看起来几乎是相同的代码,是吗?

我在开发服务器或浏览器中没有收到任何错误 :(

请您参考如下方法:

您需要将宣传列表传递给当前模板的上下文;包含模板与包含模板的关联(如果这首先有意义) View 几乎没有关系:

def post_list(request): 
    posts = Post.objects.all() 
    propagandas = Propaganda.objects.all() 
    return render(request, 'blog/post_list.html', {'posts': posts, 'propagandas': propagandas})