Python 创建&;在Django中更新用户配置文件

Python 创建&;在Django中更新用户配置文件,python,django,Python,Django,这里的Django新手在医生面前蹒跚而行。我正在尝试使用Django的“UserProfiles”创建一个用户配置文件,但是在找到基于Django文档设置代码的正确方法时遇到了一些问题 这是我的代码,基于文档。(创建用户配置文件100%来自文档) 设置和保存这些字段的正确方法是什么 例如,如果我将用户和用户配置文件模型都放在一个表单中(例如,在注册表单中),我将如何首先创建并更新所有这些模型,然后再最终保存?当需要保存注册表单中的数据时,可以调用profile.User.save(),然后调用p

这里的Django新手在医生面前蹒跚而行。我正在尝试使用Django的“UserProfiles”创建一个用户配置文件,但是在找到基于Django文档设置代码的正确方法时遇到了一些问题

这是我的代码,基于文档。(创建用户配置文件100%来自文档)

设置和保存这些字段的正确方法是什么


例如,如果我将用户和用户配置文件模型都放在一个表单中(例如,在注册表单中),我将如何首先创建并更新所有这些模型,然后再最终保存?

当需要保存注册表单中的数据时,可以调用profile.User.save(),然后调用profile.save()

在最终保存之前,我如何首先创建、然后更新所有这些内容

这些不是单独的步骤。在Django中创建或更新记录时,将其保存到数据库中

对于注册表,我建议您将其设置为
User
记录上的
ModelForm
,然后指定要保存到配置文件中的其他字段,并在save函数中单独保存它们,如

class RegistrationForm(forms.ModelForm):
    location = forms.CharField(max_length=100)
    # etc -- enter all the forms from UserProfile here

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email', and other fields in User ]

    def save(self, *args, **kwargs):
        user = super(RegistrationForm, self).save(*args, **kwargs)
        profile = UserProfile()
        profile.user = user
        profile.location = self.cleaned_data['location']
        # and so on with the remaining fields
        profile.save()
        return profile

请注意,您只能在配置文件已创建为记录且已为user.Jordan提供值的情况下执行此操作。Jordan,可能我的解释不准确。我谈到了这个代码:花了我一点时间,但这确实帮助我理解了它是如何工作的。谢谢快速问题:您是否会执行类似于
cd=form.cleaned\u data->form.save(cd)
的操作来访问save函数?不。您只需将其称为
form.save()
,它就已经可以访问已清理的数据了。
class RegistrationForm(forms.ModelForm):
    location = forms.CharField(max_length=100)
    # etc -- enter all the forms from UserProfile here

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email', and other fields in User ]

    def save(self, *args, **kwargs):
        user = super(RegistrationForm, self).save(*args, **kwargs)
        profile = UserProfile()
        profile.user = user
        profile.location = self.cleaned_data['location']
        # and so on with the remaining fields
        profile.save()
        return profile