【问题标题】:Publishing Data on Screen在屏幕上发布数据
【发布时间】:2019-08-09 02:09:55
【问题描述】:

我正在学习 Django,并在此视频中进行了练习,我在 45 分钟左右起床,一切正常:https://www.youtube.com/watch?v=D6esTdOLXh4 之后,我无法像在视频。

我将新模型命名为“posts”,这与视频中将模型称为“Posts”不同,因此我调整了我的代码,而不是创建变量“posts”,而是在 view.py 中创建了 blogpost。下面我展示了模型、视图和索引的代码。问题是我可以看到布局,但它没有填充 jinja 代码中的博客文章。如果我添加静态文本,静态文本显示正常。

模型.py

   /*from django.db import models
   from datetime import datetime

   # Create your models here.

class posts(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    created_at = models.DateTimeField(default=datetime.now, blank=True)
    def __str__(self):
        return self.title
    class Meta:
        verbose_name_plural = "Posts"*/

Views.py

def index(request):
#    return HttpResponse('Hello from Posts')

    blogpost = posts.objects.all()[:10]

    context = {
        'title': 'latest posts',
        'posts': blogpost
    }

    return render(request, 'posts/index.html', context)

索引.html

{% extends 'posts/layout.html' %}

{% block content %}
<h1 class="center-align red lighten-3">{{title}}</h1>
<ul class="collection">
    {% for blog in blogpost %}
        <li class="collection-item">{{blog.title}}</li>
    {% endfor %}
</ul>
{% endblock %}

因此,就像在视频中一样,它应该会在主屏幕上显示博文 1 和 2,但事实并非如此。

【问题讨论】:

    标签: python django


    【解决方案1】:

    在视图中,您正在将 posts 作为参数发送到模板。

    context = {
            'title': 'latest posts',
            'posts': blogpost
        }
    

    在模板上,您必须将for 更改为:

    {% for blog in posts %}
        <li class="collection-item">{{blog.title}}</li>
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      • 2012-07-02
      • 2012-03-01
      • 1970-01-01
      • 2016-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多