我有一个名为 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/