Django从对象创建模型示例

dl5txlt9  于 2023-02-10  发布在  Go
关注(0)|答案(1)|浏览(149)

我正在开发一个Django Daily Saving App,员工用户可以在其中创建客户账户,客户账户列表中有一个存款链接,员工用户可以在其中添加客户存款。问题是,在将客户ID获取到客户存款视图后,我想创建从ID获取客户详细信息并创建他的存款,但每次我尝试它时,我都看到:无法分配“〈django.db.models.fields.related_descriptor.ReverseOneToOneDescriptor对象在0x00000129FD8F4910〉":“存款.客户”必须是一个“配置文件”示例见下面我的模型:

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创建配置文件示例的帮助,如上所示。谢谢

0sgqnhkj

0sgqnhkj1#

问题是您在custom_deposit函数中将外键字段而不是示例传递给存款.objects.create,并尝试删除

profile = User.profile

行中还有另一个错误

acct = Account.account_number

应该是

acct = customer.account_number

相关问题