获取最后创建的用户以将用户配置文件链接到 django
当我尝试将数据添加到 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决了我自己的问题。学习 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().