与用户具有一对一关系的 Django 客户 - 如何在创建用户时为该模型创建字段?

Django Customer with onetoone relationship with User - how to create the fields for that model when creating User?

这是我的问题 - 在 django 中创建用户后,我还想创建具有 Onetoone 关系的客户。我能够使它正常工作,但是当我无法同时创建字段时,问题就开始了——dob 和 mobile。 (用户是默认的 django 用户)

我的forms.py

    class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']
    mobile = CharField(max_length=30)
    
class CreateCustomerForm(ModelForm):
    class Meta:
        model = Customer
        fields = ['mobile', 'dob']

我的models.py

class Customer(Model):
    user = OneToOneField(User, on_delete=CASCADE)
    mobile = CharField(max_length=12,null=True)
    dob = DateField(null=True)

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

我的views.py

def customer_registration(request):
    form = CreateUserForm()

    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            user = form.save()
            username = form.cleaned_data.get('username')
            group = Group.objects.get(name='customer')
            user.groups.add(group)
            Customer.objects.create(
                user=user, 
            )
            messages.success(request, 'Account was created for ' + username)
            return redirect('index')
    context = {'form': form}
    return render(request, 'signup.html', context)

我需要在该客户模型中再添加 2 个字段(dob=form.dob、mobile=form.mobile),我试图为此使用第二种形式,但它不起作用。这是我试过的:

def customer_registration(request):
    form = CreateUserForm()
    form2 = CreateCustomerForm()

    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            user = form.save()

            username = form.cleaned_data.get('username')
            group = Group.objects.get(name='customer')
            user.groups.add(group)
            if request.method == 'POST':
                form2 = CreateCustomerForm(request.POST)
                
                mobile = form2['mobile']

                Customer.objects.create(
                user=user, mobile=mobile)
                messages.success(request, 'Account was created for ' + username)
                return redirect('index')
            else:
                print('Error')
    context = {'form': form, 'form2': form2}
    return render(request, 'signup.html', context)

和:

def customer_registration(request):
    form = CreateUserForm()
    form2 = CreateCustomerForm()

    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        form2 = CreateCustomerForm(request.POST)
        if form.is_valid() and form2.is_valid():
            user = form.save()
            mobile = form2.save()
            username = form.cleaned_data.get('username')
            group = Group.objects.get(name='customer')
            user.groups.add(group)
            Customer.objects.create(
                user=user, mobile=mobile,
            )
            messages.success(request, 'Account was created for ' + username)
            return redirect('index')
    context = {'form': form, 'form2': form2}
    return render(request, 'signup.html', context)

我真的很喜欢这个。有什么想法吗?

唯一的问题是你的CreateCustomerForm没有给Customeruser字段赋值,你可以设置.user.instance包裹在第二种形式(form2):

def customer_registration(request):
    form = CreateUserForm()
    form2 = CreateCustomerForm()

    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        form2 = CreateCustomerForm(request.POST)
        if form.is_valid() and form2.is_valid():
            user = form.save()
            form2<strong>.instance.user = user</strong>  # 🖘 assign to the user of the customer
            form2.save()
            username = user.username
            messages.success(request, f'Account was created for {username}')
            return redirect('index')
    context = {'form': form, 'form2': form2}
    return render(request, 'signup.html', context)