为了账号安全,请及时绑定邮箱和手机立即绑定

Django 不提供文本内容(第一次尝试)

Django 不提供文本内容(第一次尝试)

米脂 2023-03-01 16:30:20
概括:这个特定的 Django 网络应用程序的目的是在主页上显示一些 lorem ipsum 文本,如博客文章。Django 不提供我的博文内容。我知道问题出在我的 views.py 或 urls.py(或两者)上。细节:我已经在我的 models.py 中声明了数据。我有 views.py 来实例化模型。我迁移了 sqlite 并成功登录到管理仪表板并输入了一些占位符数据。我试图让 Django 提供我在管理仪表板中输入的占位符内容,但它是空白的。这是我的测试用例的样子: https: //i.imgur.com/IuOl3G4.jpg 为了描述它,您可以看到已解析的博客文章、日期、图像和正文 HTML 标题元素,但没有内容正在显示。这是我的应用程序的 urls.py:from django.urls import path, includefrom . import viewsurlpatterns = [   path('', views.mortems, name='home'),]我尝试将第一个 path() 参数的引号替换为 alls/landings. 我试过将 name 参数从交换home到mortems. 我也尝试使用mortem(没有s)。这些变化都没有帮助。我也试过谷歌搜索(有变化):'正文django不显示模板''django 不显示文本内容'其中出现了(除其他外)SO 问题和答案哪种声音相关但与我的问题完全不同:Django 消息框架未在模板中显示消息为什么 django 模板没有显示任何输出?这是我的应用程序的 views.py:from django.shortcuts import redirect, render, get_object_or_404from mortems.models import Mortemdef mortems(request):   mortem = Mortem.objects.order_by('-pub_date')   context = {'mortem':mortem}   return render(request, 'alls/landings.html', context)对于它的价值,以下是我模型中的相关行:class Mortem(models.Model):   title = models.CharField(max_length=161)   pub_date = models.DateTimeField()   image = models.ImageField(upload_to='media/')   body = models.TextField()   now = datetime.datetime.now()此外,这是我的模板,其中包含相关的问题行 (42-50):<h1> BLOG POST:</h1><h4>Date: {{ mortem.pub_date_preference }}</h4><br />Image: <img src="{{ mortem.image.url }}" class="img-responsive center-block" style="max-height:300px;" /><br /> <!-- Body text should go here :   -->Body Text:<p>{{ mortem.body|safe }}</p>完整的源代码在 GitHub 上。这是具体的“mortems”应用程序源代码。对于有时间的慷慨 SO 用户,我想我正在接受拉取请求。哈哈
查看完整描述

1 回答

?
慕的地6264312

TA贡献1817条经验 获得超6个赞

我认为您需要将 views.py 更新为:


from django.shortcuts import redirect, render, get_object_or_404

from mortems.models import Mortem


def mortems(request):

    mortems = Mortem.objects.all().order_by('-pub_date') # returns an iterable queryset

    context = {'mortems':mortems}  # using plural as it's a list like object

    return render(request, 'alls/landings.html', context)

在模板代码中,您需要遍历列表以一次显示一个对象。IE


<h1> BLOG POSTs:</h1>

{% for moertm in mortems} 

  <h4>Date: {{ mortem.pub_date_preference }}</h4>

  <br />

  Image: <img src="{{ mortem.image.url }}" class="img-responsive center-block" style="max-height:300px;" />

  <br />

 

  <!-- Body text should go here :   -->

  Body Text:

  <p>{{ mortem.body|safe }}</p>

{% endfor %}


查看完整回答
反对 回复 2023-03-01
  • 1 回答
  • 0 关注
  • 120 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信