Home > Net >  How to fix Cannot assign "": "" must be a "" instance? when FK model i
How to fix Cannot assign "": "" must be a "" instance? when FK model i

Time:11-14

I want to create model with view when the user is created, but I got and error:
Cannot assign "<User:test1234": "Customer_info.customer" must be a "Customer" instance.

Here are the models that I have and which I want to be created automatically when user is registered.

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)

And in views.py after registering those models are creating

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')

CodePudding user response:

As the error stats, you are assigning a User instance to a customer field which has a foreignkey relation to Customer

Your logic should look like this:

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')


  • Related