首页 > 解决方案 > 在 Django 视图模板中访问数据库表

问题描述

在特定实例中,我无法从我的 Django 应用程序中的本地 SQLite 数据库中读取对象(但能够在类似实例中从同一数据库中读取其他数据)。

其中/blog/views.py定义了两个函数,一个获取Article( index) 的所有实例,一个显示特定Article( detail) 的一些细节。detail正在按预期工作;即,我可以导航到localhost/xxxx/blog/1,它会显示Article'stitledescription. 但是,在index页面(被路由到 just localhost/xxxx/blog/)上,latest_article_list没有加载对象,因为显示“没有可用的文章”。后者意味着路由正在工作,但它只是没有读取Article.objects.all().

视图.py

from django.shortcuts import render, get_object_or_404
from .models import Article, Tags, Author


def index(request):
    """
    Will render templates/blog/index.html when called.
    This should show all articles.
    """
    latest_article_list = Article.objects.all()
    return render(request, 'blog/index.html', {'latest_article_list': latest_article_list})


def detail(request, article_id):
    """
    Render templates/blog/detail.html.
    Returns article object.
    """
    article = get_object_or_404(Article, pk=article_id)
    return render(request, 'blog/detail.html', {'article': article})

detail.html(按预期工作,返回给定主键的 Article.title 和 Article.description)

{% block content %}
<br />
<h1> {{ article.title }} </h1>
<p> {{ article.description }} </p>
{% endblock %}

index.html(未按预期工作,if latest_article_list正在评估为 FALSE)

{% extends "base.html" %}
{% load static %}

{% block content %}
<br />
<h1> Blog posts </h1>

{% if latest_article_list %}
    <ul>
    {% for article in latest_article_list %}
        <li><a href="{% url 'blog:detail' article.id %}">{{ article.description }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>
        No articles are available.
    </p>
{% endif %}
{% endblock %}

博客/models.py

from from django.db import models

default_author_id = 1
class Article(models.Model):
    title = models.CharField(max_length=100)
    # foreign key to author
    author = models.ForeignKey(Author,
                               on_delete=models.CASCADE,
                               default=default_author_id)
    description = models.TextField()
    publication_date = models.DateTimeField('Published')
    image = models.FilePathField(path='static/blog/images/')

    class Meta:
        ordering = ('publication_date',)

    def __str__(self):
        return self.title

我应该补充一点,如果我使用终端检查数据库中的Articles,我可以很好地返回它们:

py manage.py shell
from <...>/models import Article
Article.objects.all()
# <QuerySet [<Article: article1>, <Article: article2>]>

我松散地遵循官方 Django 教程

标签: pythondjangosqlite

解决方案


推荐阅读