首页 > 解决方案 > 显示来自 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>

结果我有空白页。怎么了?

标签: django

解决方案


headline_news是一个查询集,即数据库中所有新闻表单项的列表。查询集本身没有标题或图像,只有其中的单个项目有。所以你需要遍历它:

<body>
{% for headline in headline_news %}
  <h1>{{ headline.headline }}</h1>
  <img src="{{ headline.image.url }}">
{% endfor %}
</body>

另请注意,正如我在上面显示的,您需要显式使用.urlImageField 上的属性来获取 src 的值。


推荐阅读