Django模板中的动态地址查找

ca1c2owp  于 2023-11-20  发布在  Go
关注(0)|答案(1)|浏览(110)
  • 我在Django模板上有一个表单,有两个字段:POSTCODE和HOUSE_NUMBER。我在相关视图中有一个address_find()方法。
  • 我需要完整的地址,以显示当用户填写这2个字段,而不提交表单。(换句话说,当用户输入POSTCODE和HOUSE_NUMBER,在提交之前,我想检查地址与address_find()方法,并在表单下显示完整的地址)
  • 是否可以在Django模板中做到这一点?或者我需要提交表单才能做到这一点?谢谢。
mw3dktmi

mw3dktmi1#

我找到了一个解决办法:
首先需要在Django视图中添加一个端点:

# views.py
from django.http import JsonResponse

def address_lookup(request):
    postcode = request.GET.get('postcode')
    house_number = request.GET.get('house_number')
    full_address = address_find(postcode, house_number)
    return JsonResponse({'full_address': full_address})

字符串
然后需要为新视图创建一个URL模式:

# urls.py
from django.urls import path
from .views import address_lookup

urlpatterns = [
    # other patterns
    path('address_lookup/', address_lookup, name='address_lookup'),
]


最后需要编写JavaScript来处理表单输入:

<script>
    // Add event listeners to input fields
    document.getElementById('postcode').addEventListener('input', updateAddress);
    document.getElementById('house_number').addEventListener('input', updateAddress);

    function updateAddress() {
        // Get values from input fields
        var postcode = document.getElementById('postcode').value;
        var houseNumber = document.getElementById('house_number').value;

        // Make an Ajax request to the server
        var xhr = new XMLHttpRequest();
        xhr.open('GET', '/address_lookup/?postcode=' + postcode + '&house_number=' + houseNumber, true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                // Update the displayed address
                document.getElementById('fullAddress').innerText = JSON.parse(xhr.responseText).full_address;
            }
        };
        xhr.send();
    }
</script>

相关问题