Django扩展的UserProfile模型未保存我的额外信息

时间:2018-07-11 06:33:34

标签: python django

我有一个扩展contrib.auth.User的UserProfile模型,当我尝试保存它时,我添加到配置文件中的额外信息不会保存。

这是Models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, 
    related_name='profile')
    cellphone = models.CharField(max_length=20, blank=True, default='')

    def __str__(self):
        return self.user.username


    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)

和forms.py

class UserProfileForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)
    email = forms.EmailField(required=True)
    cellphone = forms.CharField(max_length=20)

    class Meta:
        model = User
        # fields = ('cellphone', )
        fields = ('username', 'cellphone', 'email', 'password', )

最后是我的view.py

def register(request):
    form = UserProfileForm(request.POST or None)
    if form.is_valid():
        user = form.save()
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user.profile.cellphone = form.cleaned_data['cellphone']
        user.set_password(password)
        user.save()
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                auth_login(request, user)
                return render(request, 'user/index.html', {'user': user})
    else:
        return render(request, 'user/register.html', {'form': form, })

我不知道为什么它不保存手机属性。

1 个答案:

答案 0 :(得分:0)

user.profile.save()行后的视图中添加user.profile.cellpone = ...