To resolve this issue, you can utilize Ajax. Take a look at the code snippet provided below:
--HTML--
{{ form.username | as_crispy_field }}
<medium id="validate_user_name" class="text-muted hidden">
<font color="red">
User Name Already Exits!
</font>
</medium><br />
--JS--
$('#id_username').on('input', function () {
var id_user_name = $(this).val();
$.ajax({
url: '{% url 'validateUserName' %}',
data: {
'username': id_user_name
},
dataType: 'json',
success: function (data) {
if (data.is_taken) {
$("#validate_user_name").show();
document.getElementById('id_username').style.borderColor = "red";
document.getElementById("btnAddUser").disabled = true;
} else {
$("#validate_user_name").hide();
document.getElementById('id_username').style.borderColor = "#e7e7e7";
document.getElementById("btnAddUser").disabled = false;
}
}
});
});
--Django--
def validate_user_name(request):
user_name = request.GET.get('username', None)
data = {
'is_taken': User.objects.filter(username=user_name).exists()
}
return JsonResponse(data)