显示来自Django数据库的数据

显示来自Django数据库的数据,django,Django,我试图显示mysql数据库中的数据。我已经使用django admin将数据上载到数据库: 这是my 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, d

我试图显示mysql数据库中的数据。我已经使用django admin将数据上载到数据库:

这是my 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)
views.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)
index.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\u news是一个查询集,即数据库中所有新闻表单项目的列表。queryset本身没有标题或图像,只有其中的单个项目有。因此,您需要对其进行迭代:

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

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

默认情况下在media文件夹中上载的属性url搜索图像,您可以使用{{headline.image.url}}

调用它。我用代码修改了我的.html,但它在浏览器中仍然是空白页面。我错过什么了吗?没有足够的信息来帮助你。查看源代码在浏览器中显示了什么?我的浏览器中的查看源代码没有看到{%for%}和{%endfor%}之间的代码部分。对不起,为了解决这个问题,我可以和你聊聊吗?这意味着模板没有得到你的对象。我认为问题在于URL:为什么有两个视图呈现index.html?请显示您的URL.py并说明您要访问的URL。博客应用程序中的URL:。项目的url,其中包含来自应用的url:。我应该删除一个呈现index.html的视图吗?