首页 > 解决方案 > 为什么模型文本不显示在 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']}),
    ]

标签: pythonhtmldjangodjango-modelsdjango-views

解决方案


context_object_name是用于将列表传递到的模板变量的名称。这样的变量名不应该有一个点 ( .)。例如,您可以使用:

class IndexView(generic.ListView):
    template_name = 'Homepage/index.html'
    model = Goods
    context_object_name = 'goods'

然后在模板中枚举goods并渲染description_textfor each good

{% for good in goods %}
     <h1 class="description"><a href="/Homepage/{{ good.id }}/">{{ good.description_text }}</a></h1>
{% endfor %}

您的ModelAdminyou 构造注册。实际上,您注册了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)

推荐阅读