问题是没有显示模型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
并为每个good
呈现description_text
:
{% forgood in goods%}
<h1 class="description"><a href="/Homepage/{{ good.id }}/">{{good.description_text}}</a></h1>
{% endfor %}
您构建的ModelAdmin
未注册。实际上,您注册了Good
模型,但没有注册ModelAdmin
,您需要定义ModelAdmin
并使用以下命令将其链接到Good
模型:
from django.contrib import admin
from .models import Goods, Question
classGoodAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['description_text', 'price_text']}),
]
# link Goods to the GoodAdmin
admin.site.register(Goods,GoodAdmin)
admin.site.register(Question)