【问题标题】:Django,html template,for loop not working as expectedDjango,html模板,for循环没有按预期工作
【发布时间】: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


    【解决方案1】:

    您需要传递该上下文:

    def index(request):
        comments = Comment.objects.order_by('-date_added')
        context ={'comments': comments}
        return render(request,'guestbook/index.html', context=context)
                                                      ^^^^^^^^^^^^^^^
    

    来自documentation of render

    上下文:要添加到模板上下文的值字典。默认情况下,这是一个空字典。如果字典中的值是 可调用,视图将在渲染模板之前调用它。

    意思是,字典中的值与渲染函数的已知参数context一起使用,这些值将被发送到模板。然后您可以通过 html 模板中的字典(作为上下文发送)的{{ key }} 或您的案例{{ comments }} 访问这些值。可以在此SO Answer 中找到有关上下文的更多信息。

    【讨论】:

    • 是否有一个很好的教程或链接可以帮助一个完整的初学者了解使用模板的最佳实践和最简单的方法(例如,让带有 css 的自定义文本输入框变得有用,使用 { {form}} 命令。
    • 不知道该推荐什么,但我认为你可以关注 django 的官方教程或 django girl 的或 YouTube 视频。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多