Home > Mobile >  Why model text is not displayed in html?
Why model text is not displayed in html?

Time:11-01

The problem is that the text of the model description_text is not displayed. And sorry for my english.

This is code of html

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

This is code of 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]

And this is code of 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

This is code of 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']}),
    ]

CodePudding user response:

The context_object_name is the name of the template variable used to pass the list to. Such variable names are not supposed to have a dot (.). You can for example use:

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

In the template, you then enumerate over the goods and render the description_text for each good:

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

Your ModelAdmin you construct is not registered. Indeed, you registered the Good model, but not with that ModelAdmin, you need to define the ModelAdmin and link it to the Good model with:

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)
  • Related