django - 显示来自 Django 数据库的数据
问题描述
我正在尝试显示来自 mysql 数据库的数据。我已经使用 django admin 将数据上传到数据库: 在此处输入图像描述
这是我的models.py:
from django.db import models
# Create your models here.
class Newsform(models.Model):
headline = models.CharField(max_length=50)
description = models.CharField(max_length=100, default='')
content = models.CharField(max_length=100, default='')
image = models.ImageField(upload_to='news_image', blank=True)
视图.py:
from django.shortcuts import render
from blog.models import Newsform
def first(request):
return render(request, 'blog/index.html')
def show_content_from_database(request):
headline_news=Newsform.objects.all()
context = {
'headline_news': headline_news
}
return render(request, 'blog/index.html', context)
索引.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>{{ headline_news.headline }}</h1>
<img src="{{ headline_news.image }}">
</body>
</html>
结果我有空白页。怎么了?
解决方案
headline_news
是一个查询集,即数据库中所有新闻表单项的列表。查询集本身没有标题或图像,只有其中的单个项目有。所以你需要遍历它:
<body>
{% for headline in headline_news %}
<h1>{{ headline.headline }}</h1>
<img src="{{ headline.image.url }}">
{% endfor %}
</body>
另请注意,正如我在上面显示的,您需要显式使用.url
ImageField 上的属性来获取 src 的值。
推荐阅读
- c# - Visual Studio 从同一网络中的另一台计算机调试 Web 应用程序
- c# - 即使我克隆列表,列表中对象的参数也会发生变化
- php - 使用 PHP 创建 chown 文件夹/文件
- excel - 社交媒体和电子邮件提取代码需要更新
- sql - 为 Oracle 函数定义一个 CLOB 输入参数(或使用 CLOB 输入参数定义一个函数)
- python - 如何使用 matplolib 设置时间序列多图配置
- android - Android:一个清单中有多个启动器
- php - Mac OS Catalina 上的 my.cnf 或 mysql.conf 在哪里?
- javascript - 在数组中添加新数据
- php - 如何解决GD库中的白屏问题?