Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在引发验证错误后使用Django表单填充表单字段_Javascript_Django - Fatal编程技术网

Javascript 在引发验证错误后使用Django表单填充表单字段

Javascript 在引发验证错误后使用Django表单填充表单字段,javascript,django,Javascript,Django,我需要帮助,我是django表单的新手,了解它是如何工作的。有一个html表单,当表单像这样提交时,我用javascript加密了值 $("#form").submit(function(){ //remplace the original value and send to the server the encrypted data $("#field1").val(encrypted_data); $("#field2").val(encrypted_data); r

我需要帮助,我是django表单的新手,了解它是如何工作的。有一个html表单,当表单像这样提交时,我用javascript加密了值

$("#form").submit(function(){
    //remplace the original value and send to the server the encrypted data
    $("#field1").val(encrypted_data);
    $("#field2").val(encrypted_data);
return true
});
我在django项目中有这个课程

class SomeForm(forms.Form):

field1 = forms.CharField(label="field 1")
field2 = forms.CharField(label="field 1")

clean_field1(self):
 data = decrypt_text(self.cleaned_data['field1'])
 p = re.compile(r'[\d]{8}')
 #validate decrypt data is a number and his lengt is more than 8
 if p.match(data) is None:
    raise forms.ValidationError("Error")

 return data
这项工作很好,问题是当数据无效时,我需要将原始值传递给字段,并且当前返回带有反加密值的字段

提前谢谢

这就是你的做法: 在基于类的视图中的post()方法中,您将遇到以下条件

if form.is_valid():
# you do whatever you want with this form
else:
# when your form raises a validation error, this snippet gets executed 
#so you need to write the following lines in the else condition to 
#repopulate your form:
context['form'] = self.form_class(self.request.POST)
return render(request, self.template_name, context)
现在,当您遇到验证错误时,您也可以在模板中看到它。 希望你觉得这个有用