无法在Django模板html中使用过滤器 [英] Cannot use filter inside Django template html

查看:79
本文介绍了无法在Django模板html中使用过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Django项目有问题.我的情况如下:

  {mainObject.subObjects.all%中subObject的%} 

这很好用,每个 subObject 都可以很好地进行迭代.我现在想要的是打印对象的子集,例如:

  {mainObject.subobjects.filter(someField = someValue)%中的subObject的%} 

到目前为止,我已经搜索了有关出现的错误的解决方案:

 无法解析其余部分:'(someField = someValue)' 

,但是没有找到关于使用过滤器时行应如何变化的解决方案.我只想调整 template.html 文件,因此,我不想对 views.py 文件进行更改(据称该文件可以很好地工作)./p>

如何实现?

解决方案

在@ Yuji'Tomira'Tomita的评论之后.

请不要在模板中添加太多逻辑,请引述 django文档:

哲学

如果您有编程背景,或者您习惯于您可能需要将编程代码直接混合到HTML中的语言请记住,Django模板系统不仅仅是Python嵌入HTML.这是设计使然:模板系统旨在表达方式,而不是程序逻辑.

更好地在视图中定义查询集并传递给模板:

视图:

  def my_view(request):...my_objects = mainObject.subobjects.filter(someField = someValue)返回render(request,'mytemplate.html',{'my_objects':my_objects}) 

模板:

  {my_objects%中子对象的%}...{%endfor%} 

希望有帮助.

I have an issue on my Django project. I have a situation as follows:

{% for subObject in mainObject.subObjects.all %}

This works nice, every subObject gets iterated nicely. What I want now is that I print a subset of the objects, something like:

{% for subObject in mainObject.subobjects.filter(someField=someValue) %}

So far I have searched solutions about the error I get:

Could not parse the remainder: '(someField=someValue)'

but did not find a solution about how the line should be different when a filter is used. I want to tweak just the template.html file, thus I don't want to make the change on views.py file (where everything supposedly would work nicely).

How to achieve this?

解决方案

Following @Yuji'Tomira'Tomita's comment..

Don't put too much logic into the template, quote from django docs:

Philosophy

If you have a background in programming, or if you’re used to languages which mix programming code directly into HTML, you’ll want to bear in mind that the Django template system is not simply Python embedded into HTML. This is by design: the template system is meant to express presentation, not program logic.

Better define the queryset in the view and pass to the template:

view:

def my_view(request):
    ...
    my_objects = mainObject.subobjects.filter(someField=someValue)
    return render(request, 'mytemplate.html', {'my_objects': my_objects})

template:

{% for subObject in my_objects %}
    ...
{% endfor %}

Hope that helps.

这篇关于无法在Django模板html中使用过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆