【问题标题】:Updating user profile after user create in Django在 Django 中创建用户后更新用户配置文件
【发布时间】:2013-03-15 18:01:17
【问题描述】:

我使用 1.4x 方法扩展了用户对象,方法是添加自定义“配置文件”模型,然后在用户保存/创建时实例化它。在我的注册过程中,我想向配置文件模型添加其他信息。视图成功呈现,但配置文件模型不保存。代码如下:

    user = User.objects.create_user(request.POST['username'], request.POST['email'], request.POST['password'])
    user.save()

    profile = user.get_profile()
    profile.title = request.POST['title']
    profile.birthday = request.POST['birthday']

    profile.save()

【问题讨论】:

  • 嗨,凯瑟琳,对不起。我应该先说谢谢。我很感激你的回答。我将完全使用 request.user 方法,但由于我在与配置文件更改相同的功能中注册用户,因此使用请求对象将不起作用。
  • 好吧,为什么不用其他方式调用它,profile=Profile(user=user)
  • 你确定 user.get_profile() 返回一个 Profile 吗?我也认为凯瑟琳向profile=Profile.objects.get(user=user)
  • get_profile() 返回什么? @PepperoniPizza 没有。@catherine 正在创建一个新的 Profile 实例。您正在尝试获取已创建的实例。
  • 大家好,很抱歉造成混乱,感谢您的帮助。我正在使用标准方法来扩展用户,方法是使用 OneToOne 字段创建并在用户创建时实例化它。因此,它应该在我 save() 用户模型时创建。但是,它似乎不存在。出于某种原因,使用 Profile.objects.filter(user=user) 选择它是可行的,我已经设法用 update() 方法解决了这个问题。 #dumbbugs

标签: python django django-models django-views django-authentication


【解决方案1】:

user 是 User 模型的一个实例。似乎您正在尝试获取一个已经存在的实例。这取决于您从 user.get_profile 返回的内容。您必须启动 UserProfile 实例。更简单的方法可能是这样的:

user_profile = UserProfile.objects.create(user=user)
user_profile.title = request.POST['title']
...
.
.
user_profile.save()

【讨论】:

    【解决方案2】:

    使用此代码更新您的 models.py

    from django.db.models.signals import post_save
    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            profile, created = UserProfile.objects.get_or_create(user=instance)
    
    post_save.connect(create_user_profile, sender=User)
    

    当你这样做时

    user.save()

    它将自动创建一个配置文件对象。那你就可以了

    user.profile.title = request.POST['title']
    user.profile.birthday = request.POST['birthday']
    user.profile.save()
    

    希望对你有帮助。

    【讨论】:

    • 感谢您的回答,对我帮助很大! :) 我有两个问题:1)我认为你在profile, created = UserProfile.objects.get_or_create(user=instance) 中将函数分配给profile,因为你想稍后在user.profile.title = request.POST['title'] 中使用它。正确的?那你为什么需要created? 2)在连接部分,我不应该需要像这样的weak=Falsepost_save.connect(create_user_profile, sender=User, weak=False)吗?谢谢!
    • 你需要创建,因为 get_or_create() 函数返回一个元组,而不是一个对象,像这样 ... object, True = get_or_create()
    猜你喜欢
    • 2012-07-14
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 2020-10-24
    • 2020-07-23
    相关资源
    最近更新 更多