英文:
Django Create Model Instance from an Object
问题
我正在开发一个Django每日储蓄应用程序,其中员工用户可以创建客户账户,并且在客户账户列表中有一个存款链接,员工用户可以在其中添加客户存款。
问题在于,在获取到客户ID并传递到客户存款视图后,我想从该ID获取客户详细信息并创建他的存款,但每次尝试时我看到以下错误:无法分配"django.db.models.fields.related_descriptors.ReverseOneToOneDescriptor object 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}'
请忽略任何缺失的表单,并帮助我从上述的客户账户ID创建一个Profile实例。谢谢。
英文:
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
答案1
得分: 0
问题在于您在custom_deposite
函数中,将外键字段传递给Deposit.objects.create
而不是传递实例,并尝试删除以下内容:
profile = User.profile
另外,还有一处错误在于以下这行:
acct = Account.account_number
应该改为:
acct = customer.account_number
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论