首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django -模型不调用数据库的内容。

问Django -模型不调用数据库的内容。
EN

Stack Overflow用户
提问于 2018-03-14 12:14:22
回答 1查看 24关注 0票数 0

我已经在models.py中创建了一个类,其中包含了我想在网站中插入的文章的信息。

代码语言:javascript
复制
from django.db import models
from django.urls import reverse 

class Article(models.Model):
    """
    Model representing an article.
    """
    title = models.CharField(max_length=200)
    authors = models.CharField(max_length=200)
    summary = models.TextField(max_length=1000, help_text='Enter a brief description of the article')
    content = models.TextField(max_length=100000)

    def __str__(self):
        """
        String for representing the Model object.
        """
        return self.title

    def get_absolute_url(self):
        """
        Returns the url to access a detail record for this article.
        """
        return reverse('article-detail', args=[str(self.id)])

之后,我使用Django的管理面板插入了一篇文章并保存了它。

然后,我创建了如下所示的index.html,调用数据库中的文章

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}{% endblock %}
</head>

<body>
  {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
  {% block content %}<!-- default content text (typically empty) -->
  <!-- Articles -->
  <div class="articles">
    <h1>Titolo: {{ article.title }}</h1>

    <p><strong>Autori:</strong> {{ article.authors }}</p>
    <p><strong>Riepilogo:</strong> {{ article.summary }}</p>
    <p><strong>Testo:</strong> {{ article.content }}</p>
  </div>
  {% endblock %}
</body>
</html>

但是,尽管在数据库中,这篇文章还是没有显示出来(见下面的打印)

​

​

EDIT1:按请求插入views.py

代码语言:javascript
复制
from django.shortcuts import render
from .models import Article

# Create your views here.
def index(request):
    """
    View function for home page of site.
    """

    # Render the HTML template index.html with the data in the context variable
    return render(
        request,
        'index.html',
    )
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-14 12:23:02

在模板上下文中不包括任何工件:

代码语言:javascript
复制
return render(
    request,
    'index.html',
)

您可以将文章包含在模板上下文中:

代码语言:javascript
复制
articles = Article.objects.all()
return render(
    request,
    'index.html',
    {'articles': articles}
)

然后,在模板中,您需要遍历文章。

代码语言:javascript
复制
<!-- Articles -->
<div class="articles">
  {% for article in articles %}
  <h1>Titolo: {{ article.title }}</h1>

  <p><strong>Autori:</strong> {{ article.authors }}</p>
  <p><strong>Riepilogo:</strong> {{ article.summary }}</p>
  <p><strong>Testo:</strong> {{ article.content }}</p>
{% endfor %}
</div>
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49277533

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档