【问题标题】:How to filter and loop through objects in a Django template如何过滤和循环遍历 Django 模板中的对象
【发布时间】:2018-08-21 06:12:43
【问题描述】:

我正在修改 Aldryn 新闻博客附带的默认 article.html 模板,以允许评论表单和该特定文章的 cmets 列表。我已经毫无问题地包含了表格。但我不知道如何查询 cmets。

已编辑

这是我的 list_cmets.html 模板:

{% load cms_tags staticfiles sekizai_tags %}
{% if comments %}
    {% for item in comments %}
    <div class="comment paragraph">
        <h4>{{ item.author }}</h4>
        <p>{{ item.comment }}</p>
        <p>{{ item.date }}</p>
    </div>
    {% endfor %}
{% else %}
    <p>No comments exist on this blog. Be the first to comment!</p>
{% endif %}

和comment_form.html

{% load cms_tags staticfiles sekizai_tags %}
<div id="comment_form">
<div class="container constrained paragraph">
    <h5>Submit a comment</h5>
    <form method="post">
        {% csrf_token %}

        {{ comment_form }}

        <input type="hidden" name="page" value="{{ article.id }}">

        <input type="submit" value="Submit Comment">
    </form>
</div>

还有models.py:

class BlogComment(models.Model):
    ip_address = models.CharField(max_length=255, verbose_name="IP Address")
    date = models.DateTimeField(default=datetime.now)
    article = models.CharField(max_length=255)
    author = models.CharField(max_length=255)
    comment = models.CharField(max_length=1000)

在views.py中我有这些:

def display_form(request):
    comment_form = CommentForm()

    return render(request, 'comment_form.html', {'comment_form': comment_form})


def get_blog_comments(request):
    qs = BlogComment.objects.all()
    context = {'comments': qs, 'another': 'test'}
    return render(request, 'list_comments.html', context)

在两个模板中,上下文变量都没有输出任何内容。我对自己做错了什么感到茫然。 django.template.context_processors.request 包含在我的 settings.py context_processors 中。

【问题讨论】:

  • 但这不是 Django 的工作方式。你完成教程了吗?您不只是定义一个函数并在模板中引用它;你需要一个视图,它将值作为模板上下文传递。
  • @DanielRoseman 好的,我有一个声明了该函数的 views.py...我不明白我还需要什么?
  • 您的观点仍然不正确。您需要将查询返回一个字典。
  • 重点不在于函数在views.py中。关键是函数是一个视图;它由一个 URL 指向,它接受一个请求,它呈现一个带有上下文的模板,并返回一个响应。您的功能不会做任何这些事情。阿兰,请做教程。

标签: django django-models


【解决方案1】:

如前所述,查询是在您的 views.py 文件中完成的。

# views.py
def get_blog_comments(request):

    if request.method == "GET":
        qs = BlogComment.objects.all()
        template = # location of template, ex. blog_list.html
        context = {'obj_list': qs}
        return render(request, template, context)

【讨论】:

  • 您所指的文档中是否有特定页面?我已经阅读了它,但似乎没有任何相关,这就是我在这里的原因。为什么要检查请求方法是否为 GET?这是单个评论的模板还是所有评论的模板?如何筛选当前文章?我的模板在传递参数(如文章名称)时是什么样的?
  • 你检查传入的请求是'GET'方法,因为你以后可能还想使用这个视图来'POST'新的cmets。为了过滤当前文章,您需要传递文章的 ID。
猜你喜欢
  • 2012-12-25
  • 2011-11-10
  • 1970-01-01
  • 2016-11-12
  • 1970-01-01
  • 2020-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多