django 如何修复无法分配“":建立FK模型时,“”必须是“”示例?

fdx2calv  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(145)

我想在创建用户时创建带有视图的模型,但我得到一个错误:
无法分配“〈User:test1234”:“Customer_info.customer”必须是“客户”示例。
这里是我的模型,我想在用户注册时自动创建。

class Customer(models.Model):
      user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
      points = models.FloatField(default = 0.0)
      ...

class Customer_info(models.Model):
      customer = models.OneToOneField(Customer, on_delete=models.CASCADE)
      deposit = models.FloatField(default = 0.0)

而在views.py注册之后那些模特们正在创造

def reg(request):
    form = CreateUserForm()
    if "register-btn" in request.POST:
        form = CreateUserForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            login(request, new_user)

            Customer.objects.create(
                user=new_user, points=0.0
            )

            Customer_info.objects.create(
                customer = new_user, deposit = 0.0  
                # HERE IS THE PROBLEM, IN THE customer field
            )

            response = redirect('profile')
            return response
    return render(request, 'main.html')
sauutmhj

sauutmhj1#

作为错误统计信息,您将User示例分配给与Customer具有外键关系的customer字段
您的逻辑应如下所示:

def reg(request):
    form = CreateUserForm()
    if "register-btn" in request.POST:
        form = CreateUserForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            login(request, new_user)

            # store the new customer in a variable
            customer = Customer.objects.create(
                user=new_user, points=0.0
            )

            Customer_info.objects.create(
                # assign it to `customer` field
                customer = customer, deposit = 0.0  
            )

            response = redirect('profile')
            return response
    return render(request, 'main.html')

相关问题