编写user.get_profile()自定义函数,如果没有,则应创建auth配置文件

时间:2013-11-27 21:28:45

标签: python django

我正在尝试编写自定义get_profile()函数,该函数应为通过管理员注册的用户或未调用post_save的任何其他方式创建用户配置文件。

我该如何开始?

2 个答案:

答案 0 :(得分:1)

我有点困惑。您是否尝试让用户创建帐户并登录?然后使用django-registration,这很容易,开箱即用。

答案 1 :(得分:1)

我猜你有一个模型来处理这样的用户档案:

class UserProfile(models.Model):
    """Contains user profile fields not provided by User model"""
    user = models.OneToOneField(User)
    # Defined User profile fields like picture, phone, etc

所以添加以下行(可能在UserProfile模型之后的models.py中):

User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])

允许访问用户的个人资料(例如,在模板中:{% user.profile.phone %}),如果不存在则允许创建。

这就是我在网站上解决了你所描述的问题的方式。

希望这有帮助