【发布时间】:2019-08-30 15:16:06
【问题描述】:
我正在尝试将 for 循环应用于以下 html(在 Django 项目中),以使“名称”和“评论”字段在 html 视图上重复。
当我插入模板代码时,即:
{% for c in comments %}
{% endfor %}
在我要重复的内容的任一侧,它只会使名称和 cmets 完全消失,并且没有达到预期的结果。
文件的相关部分如下:
index.html(主 html 页面)
{% load static %}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="{% static 'guestbook/styles.css' %}">
</head>
<body>
<h1>The world's guestbook</h1>
<p><a href="{% url 'sign' %}">Sign </a>the guestbook</p>
{% for c in comments %}
<h2>Name</h2>
<p>This the message that the user leaves.</p>
{% endfor %}
</body>
</html>
views.py(在留言簿应用中)
from django.shortcuts import render
from .models import Comment
# Create your views here.
def index(request):
comments = Comment.objects.order_by('-date_added')
context ={'comments': comments}
#name=Name.objects.order_by('-date_added')
return render(request,'guestbook/index.html')
def sign(request):
return render(request,'guestbook/sign.html')
models.py 文件
from django.db import models
from django.utils import timezone
# Create your models here.
class Comment(models.Model):
name=models.CharField(max_length=20)
comment=models.TextField()
date_added=models.DateTimeField(default=timezone.now)
def __str__(self):
return self.name
我正在编写一个教程,其中这是推荐的代码,并且预期的结果符合预期 - 我注意到我的 html 模板没有 div 标签,想知道这是否是个问题?如果有,如何解决?
【问题讨论】:
标签: html django loops templates model