在键入时如何验证Django表单字段?例如,对于用户名字段,我要检查此用户名是否已经存在
def clean_username(self):
username = self.cleaned_data['username']
if User.objects.filter(username=username).exists():
raise ValidationError("Entered username already exists")
return username
答案 0 :(得分:2)
您可以使用Ajax解决此问题,请查看下面的代码;
- 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)