1
我有一個名爲UserProfile
模型定義爲在Django的模板中是否可以將參數傳遞給模型類的方法?
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 %}
假設我編寫了一個可以接受任意數量參數(用於用戶類型)的自定義模板標籤。所以我可以像'{%has_user_types user'ad'「」mo「」pm「%}'一樣使用它。但我真正想要做的只是讓標籤返回「True」或「False」。那麼是否有可能像'{%has_user_types user'te'as is_tenant%}'做一些事情,然後做'{%if is_tenant%} ...'? – hobbes3
「在上下文中設置變量」「作業標籤」 –
糟糕,我不應該問*是否有可能...... *。我打算問*我應該*還是有更好的方法來做到這一點?當我寫第一條評論時,我已經閱讀了[template tags](https://docs.djangoproject.com/en/dev/howto/custom-template-tags/)上的文檔。謝謝你的幫助! – hobbes3