我已經設定了一個包含一些屬性的模型,并且可以通過 views.py 中的 slug 獲取模型。但是,我無法將其屬性呈現到模板中。我錯過了什么?
模型.py
class article(models.Model):
title = models.CharField(max_length=200)
content = RichTextUploadingField()
slug = models.SlugField(unique=True, max_length=200)
def __str__(self):
return self.title
視圖.py
def post_details(request, slug):
details = get_object_or_404(article, slug=slug)
context = {
details: 'details'
}
return render(request, 'post_details.html', context)
網址.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('<slug:slug>/', views.post_details, name='post_details')
]
我已經設定了一個 URL 來通過 index.html 中的 slug 獲取文章模型的資料
<h4 class="title"><a href="{% url 'post_details' article.slug %}">{{ article.title }}</a></h4>
post_details.html
<h2>{{ details.slug }}</h2>
我可以通過 slug 訪問此模板,但無法使用“詳細資訊”標簽獲取任何屬性
uj5u.com熱心網友回復:
你得到了關鍵:在你的contextdict 中以錯誤的方式評估views.py:
context = {
details: 'details'
}
# should be:
context = {
'details': details
}
您的版本有一個帶有實際模型實體鍵的字典,指向字串的值"details",這與您想要的相反:-)
它“有效”(不會導致錯誤),因為模板在訪問背景關系變數時會默默地忽略丟失的鍵/屬性。
您可以在模板配置上設定一個特殊設定string_if_invalid,以便在不存在 var 時使其更加明顯,盡管正如它所提到的,您不能一直啟用它,因為許多其他代碼都希望這種靜默為空-字串行為。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/498004.html
上一篇:如何保護某些端點不讓用戶直接在django中訪問它?
下一篇:將Django-tables2與基于類的視圖和非默認資料庫一起使用會拋出“NameError:name'TypeError'isnotdefined”
