問題是模型 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']}),
]
uj5u.com熱心網友回復:
本context_object_name是用來傳遞串列的模板變數的名稱。此類變數名稱不應帶有點 ( .)。例如,您可以使用:
class IndexView(generic.ListView):
template_name = 'Homepage/index.html'
model = Goods
context_object_name = 'goods'
在模板中,您然后列舉goods并description_text為每個渲染good:
{% for good in goods %}
<h1 class="description"><a href="/Homepage/{{ good.id }}/">{{ good.description_text }}</a></h1>
{% endfor %}
您ModelAdmin構建的未注冊。實際上,您注冊了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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/343299.html
標籤:Python html 姜戈 django-models django-views
下一篇:在下拉串列中使用名稱
