在模板中使用userena配置文件

时间:2013-01-26 18:29:16

标签: django django-users

有没有办法从模板中的userena个人资料中获取个人资料信息?是否有某种变量自动传递?

例如:我可以像这样得到django用户变量:

{% if user.is_authenticated %}
   Hey {{ user.username }}.
{% endif %}

因为这是与每个请求一起传递的。

是否有内置方法可以对userena配置文件执行相同的操作而不会在每个视图中传递配置文件?理想情况下,我想做某事。像这样:

{% if user.is_authenticated %}
    {% if user.profile.likes_cookies %}
       Hey cookiemonster
    {% endif %}
{% endif %}

1 个答案:

答案 0 :(得分:2)

您可以直接在模板中访问用户的个人资料。

假设我已经定义了我的userena配置文件,如下所示:

class MyProfile(UserenaBaseProfile):
    user = models.OneToOneField(User,
                                unique=True,
                                verbose_name=_("user"),
                                related_name="my_profile")
    # Example of adding additional fields below.
    likes_cookies = models.BooleanField(_("likes cookies"))

具有User类的OneToOneField上的related_name是这里的重要部分,因为它是您访问userena配置文件的方式。

现在,您可以在模板中按如下方式访问配置文件:

{% if user.is_authenticated %}
    {% if user.my_profile.likes_cookies %}
       Hey cookiemonster
    {% endif %}
{% endif %}
相关问题