Django Create Model Instance from an Object

Question:

I am working on a Django Daily Saving App where Staff User can create Customer Account, and from the list of the Customer Accounts there is link for Deposit where staff user can add customer deposit.
The issue is that after getting the customer id to the customer deposit view, I want to create get the customer details from the ID and create his deposit but anytime I try it I see: Cannot assign "<django.db.models.fields.related_descriptors.ReverseOneToOneDescriptor object at 0x00000129FD8F4910>": "Deposit.customer" must be a "Profile" instance
See below my Models:

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

Here are my views:

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)

Here is my Template code the use of 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 %}  

Please ignore any missing form and help on how to make a Profile instance from the Customer Account ID as shown above. thanks

Asked By: apollos

||

Answers:

the problem is that you pass the foreign key field instead of the instance to your Deposit.objects.create in your custom_deposite function and try removing

profile = User.profile

also there is another error in line

acct = Account.account_number

it should be

acct = customer.account_number
Answered By: Super sub
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.