沿着用户输入django创建扩展条目

时间:2018-04-22 21:37:06

标签: python django forms

您好,感谢您的帮助

我有以下代码,用于在" user_profile"时创建一个新用户。部分被注释掉了。我只是想将扩展字段添加到用户。我想我很接近,但我有点失落。这样做的正确方法是什么?

现在当我运行它取消注释我得到此错误

UNIQUE constraint failed: slug_trade_app_userprofile.user_id

要清楚,在点击提交之前,数据库中不存在该用户

views.py

def signup(request):

if request.method == 'POST':

    user_form = UserForm(request.POST)
    profile_form = UserProfileForm(request.POST)

    if user_form.is_valid():

        if user_form.is_valid():
            print("1")
            #user
            created_user = user_form.save(commit=False)
            created_user.username = created_user.email
            created_user.set_password(created_user.password)
            created_user.save()
            print("2")

            #extended profile
            created_profile = profile_form.save(commit=False)
            created_profile.user = created_user
            created_profile.save()
            print("3")

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)

我尝试过这项工作的另一种方式如下。我想用更多Django正确的方式来做,但两种方式都可以。我两种方式都有同样的错误。

def signup(request):

if request.method == 'POST':

    user_form = UserForm(request.POST)
    profile_form = UserProfileForm(request.POST)

    if user_form.is_valid():


        # create user
        username = request.POST['email']
        first_name = request.POST['first_name']
        last_name = request.POST['last_name']
        email = request.POST['email']
        password = request.POST['password1']

        user = User.objects.create_user(username=username,
                            first_name=first_name,
                            last_name=last_name,
                            email=email,
                            password=password)

        #extended
        bio = request.POST['bio']
        on_off_campus = request.POST['on_off_campus']

        user_profile = UserProfile.objects.create( user=user,
                            bio=bio,
                            on_off_campus=on_off_campus)

0 个答案:

没有答案