在CustomUser
模型中有一个name
字段,当用户在Transfer
模型中输入帐号时,我希望显示该字段。这意味着验证:想象一下,你想把资金转移到某人的账户。当发送方输入接收方的账号时,我希望CustomUser
模型的name
字段实时显示在Transfer
模型的name
字段中,为此,我需要查询Account
模型并将结果发送到JsonResponse
,但我不明白为什么它说Account Not Found
即使帐户号码确实存在于数据库中。
Models.py
class Account(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
account_number = models.IntegerField()
account_balance = models.DecimalField(max_digits=12, decimal_places=6, default=0.0)
account_status = models.CharField(max_length=40, choices=ACCOUNT_STATUS)
is_accepted_for_Loan = models.BooleanField()
class Transfer(models.Model):
name = models.CharField(max_length=100)
account_number = models.IntegerField()
sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='sender_user')
receiver = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='receiver_user')
amount = models.DecimalField(max_digits=12, decimal_places=6, default=0.0)
timestamp = models.DateTimeField(auto_now_add=True)
模板
<input type="number" id="account_number" placeholder="Receiver's Account Number">
<p>Receiver Name: <span id="receiver_name"></span></p>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('#account_number').on('input', function() {
let url = "{% url 'Get_Receiver_Infor' %};
var accountNumber = $(this).val();
if (accountNumber.length > 9) {
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
success: function(data) {
$('#receiver_name').text(data.name);
},
error: function() {
$( '#receiver_name').text('Account Not Found');
}
});
} else {
$('#receiver_name').text('Something Went Wrong Please Try Again');
}
});
});
</script>
浏览次数
from django.http import JsonResponse
def get_receiver_info(request):
if request.method == 'POST':
receiver_account_number = request.POST.get('account_number')
try:
receiver_account = Account.objects.get(account_number=receiver_account_number)
receiver_user = receiver_account.user
response_data = {
'name': receiver_user.name,
}
return JsonResponse(response_data)
except Account.DoesNotExist:
return JsonResponse({'error': 'Account not found'}, status=404)
return render (request, 'Profile/transfer.html')
1条答案
按热度按时间e5njpo681#
您没有将帐号作为数据传递,因此出现错误:
注意:请使用
request.POST['account_number']
而不是request.POST.get('account_number')
。使用.get(…)
通常只能隐藏错误,而不能隐藏问题:事实上,如果密钥丢失,它将工作。但是如果确实需要该键的值,那么它只会在稍后的过程中导致更多的麻烦。