Django Создание экземпляра модели из объекта

Я работаю над Django Daily Saving App, в котором пользователь может создать счет клиента, а в списке счетов клиента есть ссылка на депозит, где пользователь может добавить депозит клиента. Проблема в том, что после получения идентификатора клиента в представлении депозита клиента, я хочу получить данные клиента из идентификатора и создать его депозит, но каждый раз, когда я пытаюсь это сделать, я вижу: Невозможно присвоить объект "<django.db.models.fields.related_descriptors.ReverseOneToOneDescriptor at 0x00000129FD8F4910>": "Deposit.customer" должен быть экземпляром "Profile". Смотрите ниже мои модели:

class Profile(models.Model):
    customer = models.OneToOneField(User, on_delete=models.CASCADE, null = True)
    surname = models.CharField(max_length=20, null=True)
    othernames = models.CharField(max_length=40, null=True)
    gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True)
    address = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=11, null=True)

    image = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to ='profile_images', 

)
    def __str__(self):
        return f'{self.customer.username}-Profile'


class Account(models.Model):
    customer = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    account_number = models.CharField(max_length=10, null=True)
    date = models.DateTimeField(auto_now_add=True, null=True) 

    def __str__(self):
        return f' {self.customer} - Account No: {self.account_number}'

class Deposit(models.Model):
    customer = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
    acct = models.CharField(max_length=6, null=True)
    staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    deposit_amount = models.PositiveIntegerField(null=True) 
    date = models.DateTimeField(auto_now_add=True)  

    def get_absolute_url(self):
        return reverse('create_account', args=[self.id])

    def __str__(self):
        return f'{self.customer} Deposited {self.deposit_amount} by {self.staff.username}'

Вот мои взгляды:

def create_account(request): 
    if searchForm.is_valid():
        #Value of search form
        value = searchForm.cleaned_data['value']
        #Filter Customer by Surname, Othernames , Account Number using Q Objects
        user_filter = Q(customer__exact = value) | Q(account_number__exact = value)
        #Apply the Customer Object Filter
        list_customers = Account.objects.filter(user_filter) 
    
    else:
        list_customers = Account.objects.all()

    context = {
        
        
        'customers':customers,
        
        }
    return render(request, 'dashboard/customers.html', context)

def customer_deposit(request, id):
    try:
        #Check the Customer ID in DB
        customer = Account.objects.get(id=id)
        #Customer Account
        acct = Account.account_number
        profile = Profile.objects.get(customer=customer.customer.id)
        profile = User.profile
        
    except Account.DoesNotExist:
        messages.error(request, 'Customer Does Not Exist')
        return redirect('create-customer')
    else:
if request.method == 'POST':
            #Deposit Form
            form = CustomerDepositForm(request.POST or None)
            
            if form.is_valid():
                #Get  Deposit Details for form variable
                amount = form.cleaned_data['deposit_amount']
                
                #Set Minimum Deposit
                minimum_deposit = 100
                #Check if Customer Deposit is Less than the Minimum Deposit
                if amount < minimum_deposit:
                    messages.error(request, f'N{amount} is less than the Minimum Deposit of N{minimum_deposit}')
                else:
                    #Add Customer Deposit
                    credit_acct = Deposit.objects.create(customer=profile, acct=acct, staff=user, deposit_amount=amount)
                    #Save the Customer Deposit
                    credit_acct.save()
                
                    

                    context.update(  {
                    'amount':amount,
                    
                    'count_accounts':count_accounts,
                    })
                    
                    messages.success(request, f'N{amount} Deposited to Account {acct} Successfully.')
                    
                    return render(request, 'dashboard/deposit_slip.html', context)
                
        else:
            form = CustomerDepositForm()
        context.update(  {
                
                'customer':customer,
                
                })
        return render(request, 'dashboard/deposit.html', context)

Вот мой код шаблона, в котором используется контекст.

{% for customer in customers %}  
              <tr>
                <td>{{ forloop.counter }}</td>
                <td>{{ customer.account_number  }}</td> 

                {% if customer.customer.profile.surname == None %}

                <td> <a class="btn btn-danger" href=" {% url 'update-customer' customer.customer.id %} ">Update Customer Details.</a> </td>

                {% else %}
                
                <td>{{ customer.customer.profile.surname }} {{ customer.customer.profile.othernames }}</td>
                
                <td>{{ customer.customer.profile.phone }}</td>

                <td><a class="btn btn-success btn-sm" href="{% url 'account-statement' customer.customer.id %}">Statement</a></td>
                
                
                
                <td><a class="btn btn-danger btn-sm" href="{% url 'dashboard-witdrawal' customer.id  %}">Withdraw</a></td>
                


                <th scope="row"><a class="btn btn-success btn-sm" href="{% url 'create-deposit' customer.id %}">Deposit</a></th>
                {% endif %}
                
                
              </tr>
              {% endfor %}  

Прошу проигнорировать отсутствующую форму и помочь, как сделать экземпляр профиля из ID счета клиента, как показано выше, спасибо

проблема в том, что вы передаете поле внешнего ключа вместо экземпляра в Deposit.objects.create в вашей функции custom_deposite и пытаетесь удалить

profile = User.profile

также есть еще одна ошибка в строке

acct = Account.account_number

должно быть

acct = customer.account_number
Вернуться на верх