首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Django创建用户配置文件(如果不存在

Django创建用户配置文件(如果不存在
EN

Stack Overflow用户
提问于 2010-09-14 16:59:57
回答 3查看 12K关注 0票数 18

我在代码中的许多地方使用了request.user.get_profile()。然而,并非所有用户都有与其帐户关联的用户配置文件。如果他们没有用户配置文件,我可以在调用request.user.get_profile()时自动创建用户配置文件,而不必更改我的每个request.user.get_profile()调用。也许是用信号或者别的什么。

我的问题是,我使用单点登录登录,所以如果有人登录到另一个系统,然后转到我的网站,他们会登录,但不会创建用户配置文件(当他们登录时,我会创建用户配置文件)。

EN

回答 3

Stack Overflow用户

发布于 2012-02-22 06:59:14

我在这个网站上找到了这个我喜欢使用的解决方案:http://www.turnkeylinux.org/blog/django-profile

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

使用这样的属性看起来比定义一个新方法更干净,但我同意检查您的代码库并将user.get_profile()引用更改为user.profile引用是一件痛苦的事情。

话又说回来,这不就是你的全局文件搜索和替换功能的用途吗?

票数 3
EN

Stack Overflow用户

发布于 2012-05-02 13:25:15

基于bskinner的答案并响应sqwerty的评论,您可以使用以下内容:

def get_or_create_profile(user):
    """
    Return the UserProfile for the given user, creating one if it does not exist.

    This will also set user.profile to cache the result.
    """
    user.profile, c = UserProfile.objects.get_or_create(user=user)
    return user.profile

User.profile = property(get_or_create_profile)

因此,这将创建一个配置文件,如果需要,然后User.profile.field = "deep"然后User.profile.save()工作。

票数 2
EN

Stack Overflow用户

发布于 2015-02-13 06:33:58

这里有一个快速管理命令,可以用来为任何缺少默认配置文件的用户创建默认配置文件。准备就绪后,您可以随时运行./manage.py missing_profiles,或者将其添加到cron作业中,等等。

from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from people.models import Profile

'''
Create default profiles for any User objects that lack them.
'''


class Command(BaseCommand):
    help = "Create default profiles for any User objects that lack them."

    def handle(self, *args, **options):
        users = User.objects.filter(profile=None)
        for u in users:
            Profile.objects.create(user=u)
            print("Created profile for {u}".format(u=u))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3707398

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档