【问题标题】:TemplateSyntaxError at /blog/second Invalid filter: 'get_val'/blog/second 处的 TemplateSyntaxError 过滤器无效:'get_val'
【发布时间】:2021-01-22 22:14:43
【问题描述】:

这是我在将 cmets 和回复分开并将回复更改为字典的视图中的功能

def blogpost(request,slug):

    variable=Post.objects.filter(slug=slug).first()
    comments=Comments.objects.filter(post=variable,parent=None)
    replys=Comments.objects.filter(post=variable).exclude(parent=None)
    replyDict={}
    for reply in replys:
        if reply.parent.sno not in replyDict.keys():
            replyDict[reply.parent.sno]=[reply]
        else:
            replyDict[reply.parent.sno].append(reply)
    return render(request,"blog/blogpost.html",{'blog':variable,'comments':comments,'user':request.user,"replys":replyDict})

这里显示我的回复

 {% for reply in replys|get_val:comment.sno %}
            {{reply}}
            {% endfor %}

在这里,我正在解析我的字典,为 sno 找到合适的配对 从 django 导入模板

register=template.Library()

@register.filter(name='get_val')
def get_val(dict,key):
    return dict.get(key)

【问题讨论】:

  • 您缺少{% load %} 标签。例如in the docs{% load poll_extras %}
  • 感谢 Alasdair 成功

标签: django django-models django-rest-framework django-views django-templates


【解决方案1】:
def blogpost(request,slug):

    variable=Post.objects.filter(slug=slug).first()
    comments=Comments.objects.filter(post=variable,parent=None)
    replys=Comments.objects.filter(post=variable).exclude(parent=None)
    replyDict={}
    for reply in replys:
        if reply.parent.sno not in replyDict.keys():
            replyDict[reply.parent.sno]=[reply]
        else:
            replyDict[reply.parent.sno].append(reply)
    return render(request,"blog/blogpost.html",{'blog':variable,'comments':comments,'user':request.user,"replys":replyDict})

【讨论】:

    猜你喜欢
    • 2013-06-17
    • 2013-07-24
    • 2021-06-04
    • 2016-04-06
    • 2011-08-02
    • 2011-12-15
    • 2013-04-09
    • 2021-10-21
    • 2014-08-18
    相关资源
    最近更新 更多