jquery Django:-实时名称显示问题:尽管存在帐号,但“未找到帐户”

w41d8nur  于 2023-10-17  发布在  jQuery
关注(0)|答案(1)|浏览(81)

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')
e5njpo68

e5njpo681#

您没有将帐号作为数据传递,因此出现错误:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    $(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',
                    data: {account_number: accountNumber},
                    headers: {'X-CSRFToken': getCookie('csrftoken')},
                    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>

注意:请使用request.POST['account_number']而不是request.POST.get('account_number')。使用.get(…)通常只能隐藏错误,而不能隐藏问题:事实上,如果密钥丢失,它将工作。但是如果确实需要该键的值,那么它只会在稍后的过程中导致更多的麻烦。

相关问题