简体   繁体   English

如何在 Django 模板中设置过滤器

[英]How to set filters in Django template

I have a custom template tag which verifies the user's group but when I use it as a template filter in an HTML template it is bugging out all over the place.我有一个自定义模板标签来验证用户的组,但是当我将它用作 HTML 模板中的模板过滤器时,它到处都是窃听器。

This is my custom template tag:这是我的自定义模板标签:

@register.filter(name='is_in_group')
def is_in_group(user, group_name):
    group = Group.objects.get(name=group_name)
    return True if group in user.groups.all() else False

This is the first filter in the template - which is letting every user through (even users outside these groups):这是模板中的第一个过滤器——它允许每个用户通过(甚至是这些组之外的用户):

{% if request.user|is_in_group:"food bev supervisor"  or "casino supervisor" or "security supervisor" or "cage supervisor" %}

But if I change the ordering to:但是,如果我将顺序更改为:

{% if request.user|is_in_group:"casino supervisor" or "food bev supervisor" or "security supervisor" or "cage supervisor" %}

... the code fails (lets no users through). ...代码失败(不让任何用户通过)。

If I set only one group as such:如果我只设置一个组:

{% if request.user|is_in_group:"food bev supervisor" %}

then the filter works correctly (but I cannot set more than one group).然后过滤器正常工作(但我不能设置多个组)。

Is this a bug in Django?这是 Django 中的错误吗? What is the best way around this?解决这个问题的最佳方法是什么?

I was able to solve this by applying the filter to each variable as such:我能够通过将过滤器应用于每个变量来解决这个问题:

{% if request.user|is_in_group:"food bev supervisor" or request.user|is_in_group:"casino supervisor" or request.user|is_in_group:"security supervisor" or request.user|is_in_group:"cage supervisor" %}

It isn't pretty or Pythonic but at least it works.它并不漂亮或 Pythonic,但至少它有效。 The Django convention is a little odd here but after trying a lot of different ways I believe this one is the correct way. Django 约定在这里有点奇怪,但在尝试了很多不同的方法之后,我相信这是正确的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM