在Django中创建用户后更新用户资料
我通过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()
2 个回答
1
这里的"user"是一个用户模型的实例。看起来你想获取一个已经存在的实例。具体情况取决于你从"user.get_profile"中返回了什么。你需要创建一个用户资料的实例。一个简单的方法可以是这样:
user_profile = UserProfile.objects.create(user=user)
user_profile.title = request.POST['title']
...
.
.
user_profile.save()
6
用这段代码更新你的 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()
希望这对你有帮助。