Skip to main content
 首页 » 编程设计

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

2025年05月04日38JustinYoung

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

    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() 

请您参考如下方法:

用这段代码更新你的 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.profile.title = request.POST['title'] 
user.profile.birthday = request.POST['birthday'] 
user.profile.save() 

希望对您有所帮助。