尝试以Django的形式将User扩展到UserProfile

时间:2018-04-19 19:29:22

标签: python django forms

嗨,我正在努力让这个表格起作用。当我尝试运行我的程序时,它会打印(" 4")然后抛出错误

UNIQUE constraint failed: slug_trade_app_userprofile.user_id

要清楚,我在创建的新用户在单击表单上的提交之前不存在

似乎个人资料正在尝试再次创建一个新用户,但由于(我认为)用户创建了一个新用户,该用户已经存在其抛出错误。 HELP !!

Views.py

def signup(request):
if request.method == 'POST':
    user_form = UserForm(data=request.POST)
    profile_form = UserProfileForm(data=request.POST)

    if user_form.is_valid() and profile_form.is_valid():
        print("1")
        user = user_form.save(commit=False)
        user.save()

        print("2")
        profile = profile_form.save(commit=False)
        print("3")
        profile.user = user
        print("4")
        profile.save()
        print("5")

        user = authenticate(username=user_form.cleaned_data['email'],
                            password=user_form.cleaned_data['password1'],
                            )

        login(request, user)
        return redirect('/home')
else:
    user_form = UserForm()
    profile_form = UserProfileForm()

    return render(request, 'slug_trade_app/signup.html', {'user_form': user_form, 'profile_form': profile_form})

models.py

class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField(upload_to='static/profile_pictures', blank=True )
bio = models.TextField(max_length=500, blank=True)
on_off_campus = models.CharField(max_length=3,
                            default="on",
                            choices=CAMPUS_STATUS)

forms.py

class UserForm(UserCreationForm):
email = forms.EmailField(required=False)

class Meta:
    model = User
    fields = (
        'first_name',
        'last_name',
        'email',
        'password1',
        'password2',
    )

def save(self, commit=True):
    user = super(UserForm, self).save(commit=False)
    user.username = self.cleaned_data['email']
    user.first_name = self.cleaned_data['first_name']
    user.last_name = self.cleaned_data['last_name']
    user.email = self.cleaned_data['email']

    if commit:
        user.save()

    return user


class UserProfileForm(forms.ModelForm):
    class Meta():
        model = UserProfile
        fields = ('profile_picture', 'bio', 'on_off_campus')

1 个答案:

答案 0 :(得分:0)

尝试profile_form = UserProfileForm(instance=request.user)我相信profile.user = user应该是profile.user = request.user,否则用户会引用用户表单而不是用户实例