德扬戈。模型未显示在模板中

2024-04-26 00:27:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

models.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

views.py

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'

模板

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

3条回答

在模板中尝试以下操作:

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

你不能使用MyDate,你必须使用你的context_object_name:mydate

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

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

在这方面:

context = {
  'my_date' : my_date,
}

模板中的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  %}

相关问题 更多 >