python - 是否可以将参数传递给 Django 模板中的模型类方法?

标签 python django django-templates

我有一个名为 UserProfile 的模型,定义为

class UserProfile(models.Model):
    user       = models.OneToOneField(User, related_name='userprofile_from_user')
    user_types = models.ManyToManyField(UserType, related_name='userprofiles_from_user_types', null=True, blank=True)

    def has_user_types(self, user_types):
        return self.user_types.filter(name__in=user_types).count()

UserType 定义为

class UserType(models.Model):
    TYPE_CHOICES = (
        ('ad', 'administrator'   ), # 1
        ('mo', 'moderator'       ), # 2
        ('vi', 'viewer'          ), # 3
        ('pm', 'property manager'), # 4
        ('po', 'property owner'  ), # 5
        ('vm', 'vendor manager'  ), # 6
        ('ve', 'vendor'          ), # 7
        ('te', 'tenant'          ), # 8
    )

    name = models.CharField(max_length=2, choices=TYPE_CHOICES)

我希望能够使用UserProfile的方法has_user_types()。从某种意义上说,我会做类似的事情

if user.profile.has_user_types(['ad', 'mo', 'pm']):
    # The user is any combination of an administrator, moderator, or property manager.

但是我可以在模板中做同样的事情吗?我专门检查了一些用户类型,所以我想做一些类似的事情

{% if user.profile.has_user_types(['te']) %}

我知道我可以简单地在模型中定义另一个名为 is_tenant() 的方法(不带参数),但我也想检查其他用户类型,我想知道是否可以合并 has_user_types()

附带问题:如果 Django 的默认模板无法做到这一点,那么可以 Jinja2做吗?

<小时/>

解决方案

感谢伊格纳西奥·巴斯克斯-艾布拉姆斯的帮助!

custom_tags.py:

@register.assignment_tag
def has_user_types(user_pk, *args):
    user = User.objects.get(pk=user_pk)

    return user.profile.has_user_types(args)

模板:

{% load has_user_types from custom_tags %}

{# I pass the pk because I want to be able to pass any user, not just request.user #}
{% has_user_types user.pk "te" as is_tenant %}
{% if is_tenant %}
    {# Show something #}
{% endif %}

最佳答案

没有。写一个custom filter or template tag检查它们。

关于python - 是否可以将参数传递给 Django 模板中的模型类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10509441/

相关文章:

javascript - Django Python - Javascript 动态表对行进行排序

django - 如何格式化具有特定位数的数字?

django - 在Django管理员更改列表中显示未转义的HTML字符串

python - 如何在Python中漂亮地打印xml而不生成DOM树?

python - verbose_name_plural 在模型中出乎意料?

python - 使用 Levenshtein 距离作为 Python 中的启发式算法生成字符串的爬山算法?

python - Django 过滤来自自定义聚合函数的注释

python - Django "TemplateDoesNotExist "错误但 "Using loader django.template.loaders.app_directories.Loader"文件存在

python - Swift 序列化使用 Python 生成的稀疏矩阵

OS X Yosemite 上的 Python 解释器——使用哪一个?