用户在Django中创建后更新用户配置文件

Wan*_*tal 1 python django django-models django-views django-authentication

我通过添加自定义"配置文件"模型,然后在用户save/create上实例化,使用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()
Run Code Online (Sandbox Code Playgroud)

You*_*wad 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)
Run Code Online (Sandbox Code Playgroud)

现在当你这样做

user.save()

它会自动创建一个配置文件对象.那么你可以做到

user.profile.title = request.POST['title']
user.profile.birthday = request.POST['birthday']
user.profile.save()
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.