【问题标题】:Why model text is not displayed in html?为什么模型文本不显示在 html 中?
【发布时间】:2021-12-15 05:57:30
【问题描述】:

问题是model 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']}),
    ]

【问题讨论】:

标签: python html django django-models django-views


【解决方案1】:

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

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

然后在模板中枚举goods 并为每个good 渲染description_text

{% for good 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

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)

【讨论】:

  • 非常感谢,但它不起作用
  • @Licrencie:IndexView 中的get_queryset 方法没有意义(以及其他方法),尤其是因为get_queryset 返回的对象是不同的模型。你删除了这些吗?
  • 我删除了这部分代码,它可以工作,非常感谢!!
猜你喜欢
  • 2019-07-11
  • 2019-03-14
  • 1970-01-01
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 2011-08-14
  • 2013-05-28
相关资源
最近更新 更多