[英]Django. Model not showing up in template
我正在制作我的第一个 Django 项目,并在模板中添加了一个 model,但是,当我运行它时,我没有看到任何东西。 但是当我检查页面时,我看到 model 中每个条目都有一个 h2 标签。
模型.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
视图.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 %}
那是因为您没有将上下文传递给模板。 像这样写:
return(request, 'noob/clueless-me.html' context)
在上下文中:
context = {
'my_date' : my_date,
}
在您的模板中试试这个:
{% for date in mydate %}
<h2>Hi{{ date.hebrew_date }}</h2>
{% endfor %}
你不能使用MyDate
,你必须使用你的context_object_name
: mydate
模板中的 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 %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.