1

我仍然是 django 的新手,最近开始了一个有许多模型的项目。问题是每当我想将一个变量从我的数据库传递到我的网站模板时,当我运行网站时,我看不到我的变量,它们只是显示为空。例如,如果我在某个模型下有 10 个对象变量,当我使用 for 循环遍历有序列表(html)中的对象时,我在渲染页面上看到的所有内容都是空的项目符号。我迷路了需要帮助!!!

示例通知模型

    from django.db import models
    from django.utils import timezone
    import datetime

    class Notice(models.Model):
        headline=models.CharField(max_length=150)
        notice_text=models.TextField()
        publication_date=models.DateTimeField('date published')

        def __str__(self):
            return self.headline

风景

    class Home_pageView(generic.ListView):
        template_name = 'Notices/home_page.html'
        context_object_name = 'notice_objects'

        def get_queryset(self):
            return Notice.objects.all()

模板

    {% if notice_objects %}
    <ul>
    {% for item in notice_objects %}
    <li><a href="{% url 'notices:detail' notice.id %}">{{ notice.notice_text }}</a></li>
    {% endfor %}
    </ul>
    {% else %}
    <p>No notices are available.</p>
    {% endif %}

正如我已经提到的,当我运行上述代码时,我得到的只是与我在数据库中拥有的通知对象的数量相对应的空项目符号。我的项目中还有另一个名为 question 的模型,如果我使用相同的代码,变量会正确呈现,但我似乎没有注意到这两个模型之间的任何差异,但也许你们可以发现任何不规则的差异。否则,除了问题模型之外,我的所有其他模型都会在我的网站上呈现空项目符号。我什至认为我的数据库是问题,所以我从 postgresql 更改为 mariadb 和 sqlite 但没有任何改变。

问题模型

    from django.db import models
    from django.utils import timezone
    import datetime

    class Question(models.Model):
        headline=models.CharField(max_length=150,default=None,null=True)
        question_text=models.CharField(max_length=200)
        publication_date=models.DateTimeField('date published')
        def __str__(self):
            return self.question_text
        def was_published_recently(self):
            now = timezone.now()
            return now-datetime.timedelta(days=1) <= self.publication_date <= now 

风景

    class Home_pageView(generic.ListView):
        template_name = 'Polls/home_page.html'
        context_object_name = 'latest_question_list'

        def get_queryset(self):
            return Question.objects.all()

模板

    {% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
    <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
    {% else %}
    <p>No polls are available.</p>
    {% endif %}

提前感谢您的帮助。

4

2 回答 2

0

在你看来,写一个很细的线条结构就好了。

 class Home_pageView(generic.ListView):
    template_name = 'Notices/home_page.html'
    model=Notice

问题列表视图的类似情况,

在您的 HTML 模板中,

 {% for something in object_list %}
 {{something.notice_text}}
于 2020-09-25T12:55:38.097 回答
0

for item in ... 您使用参考而不是item参考循环notice- 这解释了您的空项目符号点。

将您的模板重写为:

<ul>
{% for notice in notice_objects %}
<li><a href="{% url 'notices:detail' notice.id %}">{{ notice.notice_text }}</a></li>
{% empty %}
<p>No notices are available.</p>
{% endfor %}
</ul>

if请注意,如果您使用empty标签,则不需要...

于 2020-10-01T07:59:40.293 回答