获取最后创建的用户以将用户配置文件链接到 django

发布于 2024-09-18 20:30:29 字数 615 浏览 3 评论 0原文

当我尝试将数据添加到 UserProfile 模型中时,我遇到了一些困难,该模型创建的目的是保存用户信息,超出了 django 内置 Auth 组件所能满足的范围。

我的问题是如何获取刚刚注册的用户实例以创建用户配置文件?我认为它会像下面这样:

# Registration form validation etc. is complete
cd = form.cleaned_data
user = User.objects.create_user(username=cd['username'], password=cd['password'])
new_user = user.save() # hoping this returns an instance of the user?
activation_key = some_random_generator()
new_profile = UserProfile(user=new_user, token=activation_key)
new_profile.save()

...但是 new_user 返回为 None ,我认为必须有一种简单的方法来访问刚刚注册的用户,而不是根据用户名/密码重新查询数据库?

我希望这足够清楚,感谢您的帮助/指导。

I've hit a bit of a wall when trying to add data to a UserProfile model created to hold user info beyond what is catered for in django's built in Auth component.

My question is how do I get an instance of the user just registered in order to create the the UserProfile? I thought it would be something like below:

# Registration form validation etc. is complete
cd = form.cleaned_data
user = User.objects.create_user(username=cd['username'], password=cd['password'])
new_user = user.save() # hoping this returns an instance of the user?
activation_key = some_random_generator()
new_profile = UserProfile(user=new_user, token=activation_key)
new_profile.save()

... but new_user is returning as None and I figure there must be an easy way to get access to the User just registered rather than re-querying the database based on the username/password?

I hope that is clear enough, thanks for any help/guidance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

追风人 2024-09-25 20:30:44

解决了我自己的问题。学习 python/django 的日子很慢。

当调用 user.save() 时,用户对象将在数据库插入后使用新信息进行更新 - 即新生成的 user.id 。所以这个用户对象本身实际上可以传递给UserProfile()。

Solved my own problem. Having a slow day learning python/django.

When user.save() is called, the user object is updated with new information after database insertion - i.e. the newly generated user.id . So this user object itself can actually be passed to UserProfile().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文