python - 在 Django 视图模板中访问数据库表
问题描述
在特定实例中,我无法从我的 Django 应用程序中的本地 SQLite 数据库中读取对象(但能够在类似实例中从同一数据库中读取其他数据)。
其中/blog/views.py
定义了两个函数,一个获取Article
( index
) 的所有实例,一个显示特定Article
( detail
) 的一些细节。detail
正在按预期工作;即,我可以导航到localhost/xxxx/blog/1
,它会显示Article
'stitle
和description
. 但是,在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
我应该补充一点,如果我使用终端检查数据库中的Article
s,我可以很好地返回它们:
py manage.py shell
from <...>/models import Article
Article.objects.all()
# <QuerySet [<Article: article1>, <Article: article2>]>
我松散地遵循官方 Django 教程。
解决方案
推荐阅读
- c++ - 按钮中图像的动态变化
- python - Jupyter 无法打开且无响应
- flutter - 如何在屏幕颤动之间绘制动画
- reactjs - 在drawend事件之后执行Openlayers select交互与draw交互
- delphi - Delphi 10 Seattle TabControl Style 像 Windows 中的 android
- node.js - Mongoose 只开启部分收藏
- pine-script - 如何克服“绘图”和“填充”功能限制
- javascript - Javascript从多个数组中查找所有重复项
- javascript - 阻止代码从 JS 中的检查元素运行?
- ffmpeg - 使用 ffmpeg 调整高清视频大小并将其裁剪为方形视频