Issue
- I have a form on Django template with 2 fields: POSTCODE and HOUSE_NUMBER. I have a address_find() method in the related view.
- I need the full address to be displayed when the user fills in these 2 fields without submitting the form. ( In other words, when user enters POSTCODE and HOUSE_NUMBER, before submitting I want to check the address with address_find() method and display the full address under the form)
- Is it possible to do that in Django templates? or do I need to submit the form to do that? Thanks.
Solution
I found a solution:
First need to add an endpoint in your Django views:
# 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})
Then need to create a URL pattern for the new view:
# urls.py
from django.urls import path
from .views import address_lookup
urlpatterns = [
# other patterns
path('address_lookup/', address_lookup, name='address_lookup'),
]
Finally need to write JavaScript to handle form input:
<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>
Answered By - msahin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.