Django的。模型未显示在模板中

时间:2020-08-19 14:19:58

标签: python django django-templates

我正在做我的第一个Django项目,并且在模板中添加了一个模型,但是,当我运行它时,我什么也没看到。但是当我检查页面时,我看到模型中每个条目的h2标签。

models.py

<img src="/storage/2020/08/18{ $product['image']  }" />

views.py

from django.db import models
from django.utils import timezone
from django.urls import reverse


class MyDate(models.Model):
    english_date = models.DateField(auto_now=False)
    hebrew_date = models.CharField(max_length=20)

    def __str__(self):
       return self.hebrew_date

模板

from django.views.generic import (TemplateView,ListView,DetailView,CreateView,UpdateView,DeleteView)
from luach.models import MyDate

class HomePage(TemplateView):
    template_name = 'new.html'

class MyDateListView(ListView):
    model = MyDate
    context_object_name = 'mydate'

3 个答案:

答案 0 :(得分:0)

那是因为您没有将上下文传递给模板。 这样写:

return(request, 'noob/clueless-me.html' context)

在上下文中:

context = {
  'my_date' : my_date,
}

答案 1 :(得分:0)

在模板中尝试一下:

{% for date in mydate %}
      <h2>Hi{{ date.hebrew_date }}</h2>
{% endfor %}

您不能使用MyDate,必须使用context_object_namemydate

答案 2 :(得分:0)

模板中的for语句中有错误,请尝试以下操作:

{% extends 'luach/base.html' %}
{% block content %}
<div class="jumbotron">
  {% for date in mydate %}
     <h2>Hi{{ date.hebrew_date }}</h2>
     {% empty %}
     <h2>Sorry, no dates in this list.</h2>    
  {% endfor %}
</div>
{% endblock  %}
相关问题