【问题标题】:Django not serving text content (First attempt)Django 不提供文本内容(第一次尝试)
【发布时间】:2020-07-09 20:04:54
【问题描述】:

总结:

这个特定的 Django Web 应用程序的目的是在主页上显示一些 lorem ipsum 文本,例如博客文章。 Django 不提供我的博客文章内容。我知道问题出在我的views.py 或urls.py(或两者)。

详情:

我已经在我的 models.py 中声明了数据。我有我的 views.py 来实例化模型。我迁移了 sqlite 并成功登录到 Admin Dashboard 并输入了一些占位符数据。

我正在尝试让 Django 提供我输入到管理仪表板的占位符内容,但它是空白的。

这是我的测试用例的样子:https://i.imgur.com/IuOl3G4.jpg 为了描述它,您可以看到已解析的博客文章、日期、图像和正文文本 HTML 标题元素,但没有显示任何内容。

这是我应用的 urls.py:

from django.urls import path, include
from . import views


urlpatterns = [
   path('', views.mortems, name='home'),
]

我尝试将第一个 path() 参数的引号替换为 alls/landings。我尝试将名称参数从home 交换为mortems。我也尝试使用mortem(没有s)。这些更改都无济于事。

我也尝试过谷歌搜索(有变体):

  • '正文 django 不显示模板'
  • 'django 不显示文本内容'

其中出现了(除其他外)SO问题和答案哪种声音相关但与我的问题完全不同:

这是我应用的views.py:

from django.shortcuts import redirect, render, get_object_or_404
from mortems.models import Mortem

def 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 上。这里是the 'mortems' app source code

对于有时间的慷慨 SO 用户,我想我正在接受拉取请求。哈哈

【问题讨论】:

  • 查询不应该是这样的:mortem = Mortem.objects.all().order_by('-pub_date')
  • 谢谢,@ManjitKumar:是的,我需要那个。我刚刚在我的视图函数中的查询调用中添加了.all().。虽然这还没有解决原来的问题。所以可能还有更多。

标签: python html django


【解决方案1】:

我认为您需要将 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)

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

<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 %}

【讨论】:

  • 感谢@Manjit Kumar 的回复!你所有的建议都是有效的。我立即将 views.py 中的“mortems”实例复数化,并将 for 循环添加到我的模板中。这是我的网络应用登陆页面现在的样子:e082f3051c81.ngrok.io 你可以在这里查看我的差异:github.com/enoren5/CC_Redact_Iter3/commit/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-01
  • 1970-01-01
  • 2022-08-15
  • 1970-01-01
  • 2014-12-17
  • 1970-01-01
相关资源
最近更新 更多