我正在尝试使用Django验证一个简单的表单,它似乎总是返回false。我通过AJAX将表单的值发送到views.py
,并在Javascript和view.py
中打印值,以确保它正确传递。
观点文件:
def change_alphabet(request):
cipher = CaesarCipher()
x = cipher.getListLetter()
y = cipher.getListLetter()
if request.is_ajax() and request.method == "GET":
print("Inside CHANGE")
formKey = caesarKey(request.GET or None)
print("Valid or not: %r " % formKey.is_valid())
integerKey = int(request.GET.get('the_key'))
print(integerKey)
if formKey.is_valid():
print(request.GET.get('the_key'))
integerKey = int(request.GET.get('the_key'))
y = cipher.setCipherLetters(integerKey)
context = { 'x': x,
'y': y,
'formKey': formKey,
}
return render(request, "content/alteredAlphabet.html", context)
else:
print(formKey.errors)
context = { 'x': x,
'y': y,
'formKey': formKey,
}
return render(request, "content/alteredAlphabet.html", context)
表格:
class caesarKey(forms.Form):
key = forms.DecimalField(max_value = 26, min_value = 1, initial = 1, required = True, error_messages={'required' : 'Please input a valid key number!'}, widget=forms.NumberInput(attrs={'class' : 'form-control', 'placeholder' : 'Key'}))
Javascript:
$("#keyButtonId").on({
click: function() {
var variable = document.getElementById('id_key');
console.log(variable.value)
$.ajax({
url: "/alteredAlphabet",
type: "GET",
data: {
CSRF: 'csrf_token',
the_key: $('#id_key').val()
},
success: function(json) {
// $('#id_key').val('0');
// console.log(json);
$('#letterSection').fadeOut('slow', function() {
$('#letterSection').html(json);
$('#letterSection').fadeIn(3000);
});
//document.getElementById('letterSection').value = json;
console.log("FUNCTION CALLED!");
}
});
}
});
打印的错误是:
<ul class="errorlist"><li>key<ul class="errorlist"><li>Please input a valid key number!</li></ul></li></ul>
更新:
用于呈现表单的模板代码:
<label for="id_key">
Key:
</label>
<form onsubmit="return false;" method="GET" id="key-form">
{% csrf_token %}
<div class="col-sm-2 col-xs-5">
{{ formKey.key }}
</div>
<button name="action" id="keyButtonId" class="btn btn-primary" value="key">Key</button>
</form>
{% if formKey.errors %}
<div class="alert alert-danger" role="alert">
<strong>{{ formKey.key.errors }}</strong>
</div>
{% endif %}
为什么它总是返回假?我错过了额外的数据绑定阶段吗?
答案 0 :(得分:2)
您在Ajax中将关键数据作为the_key
传递,但表单只需要key
。