首页 > 解决方案 > 为什么帖子不显示在主页上?

问题描述

当我在管理面板中添加帖子时,帖子不会显示在应用程序的主页上。它只显示帖子的空格,但无法在主页上显示帖子的文章。

视图.py

from django.shortcuts import render,HttpResponseRedirect
from django.contrib import messages
from django.http import HttpResponse
from .forms import SignUpForm, LoginForm
from django.contrib.auth import authenticate, login, logout
from .models import Post
# Create your views here.

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

主页.html

{% extends 'blog/base.html' %}
{% load static %}

{% block content %}

<div class="col-sm-10">
  <h3 class="text-white my-5">Home Page</h3>
    {% for post in posts %}
      <div class="jumbotron jumbotron-fluid jumbo-colour">
        <div class="container">
          <h1 class="display-4 font-weight-bold">{{posts.title}}</h1>
          <p class="lead">{{posts.desc}}</p>
        </div>
      </div>
    {% endfor %}
</div>

{% endblock content %}

模型.py

from django.db import models

# Create your models here.
class Post(models.Model):
    title = models.CharField(max_length=150)
    desc = models.TextField()

标签: djangodjango-formsdjango-viewsdjango-templatesdjango-urls

解决方案


您的代码中有错字。它应该是:

{% for post in posts %}
  <div class="jumbotron jumbotron-fluid jumbo-colour">
    <div class="container">
      <h1 class="display-4 font-weight-bold">{{post.title}}</h1>  // not posts.title
      <p class="lead">{{post.desc}}</p>  // not posts.desc
    </div>
  </div>
{% endfor %}

推荐阅读