python - 为什么模型文本不显示在 html 中?
问题描述
问题是模型 description_text 的文本没有显示出来。对不起我的英语。
这是html的代码
{% for description_text in context_object_name %}
<h1 class="description"><a href="/Homepage/{{ goods.id }}/">{{goods.description_text}}</a></h1>
{% endfor %}
这是views.py的代码
class IndexView(generic.ListView):
template_name = 'Homepage/index.html'
model = Goods
context_object_name = 'goods.description_text'
def description(self):
return self.description_text
def price(self):
return self.price_text
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.order_by('-pub_date')[:5]
这是models.py的代码
class Goods(models.Model):
description_text = models.CharField(max_length=200)
price_text = models.CharField(max_length=200)
def __str__(self):
return self.description_text
def __str__(self):
return self.price_text
这是 admin.py 的代码
from django.contrib import admin
from .models import Good
from .models import Question
admin.site.register(Good)
admin.site.register(Question)
class Good(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['description_text']}),
(None, {'fields': ['price_text']}),
]
解决方案
context_object_name
是用于将列表传递到的模板变量的名称。这样的变量名不应该有一个点 ( .
)。例如,您可以使用:
class IndexView(generic.ListView):
template_name = 'Homepage/index.html'
model = Goods
context_object_name = 'goods'
然后在模板中枚举goods
并渲染description_text
for each good
:
{% for good in goods %}
<h1 class="description"><a href="/Homepage/{{ good.id }}/">{{ good.description_text }}</a></h1>
{% endfor %}
您的ModelAdmin
you 构造未注册。实际上,您注册了Good
模型,但没有使用 that ModelAdmin
,您需要定义ModelAdmin
并将其链接到Good
模型:
from django.contrib import admin
from .models import Goods, Question
class GoodAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['description_text', 'price_text']}),
]
# link Goods to the GoodAdmin
admin.site.register(Goods, GoodAdmin)
admin.site.register(Question)
推荐阅读
- c++ - GCC 输出文件错误
- ios - iOS Swift:无法操作字符串:“String”类型的值没有成员“firstIndex”
- java - Spring data jpa查询返回错误信息
- python - 分析成员对话的数据
- jquery - 在 jquery ajax 响应函数中使用 window.location 是否安全,它不会是一个安全线程,因为它暴露在客户端
- python-3.x - 如何在没有DataFrame名称的groupby链语句中引用索引属性?
- wpf - WPF Datagrid Cell 的 DataTemplate 的更改导致不想要的结果
- sql - SQL Group 按排序结果
- c++ - 找不到 cmake 和 osx 框架
- azure-ad-b2c - 将自定义 UI 与 ADB2C 登录策略一起使用