简体   繁体   English

在提交之前在javascript中检查django表单错误的最佳方法是什么?

[英]what is the best way to check django form errors in javascript before submitting?

Actually I need a method which have same error message in javascript validation (client side) and in my django form validation (server side). 实际上我需要一个在javascript验证(客户端)和我的django表单验证(服务器端)中具有相同错误消息的方法。

I search for any django library for this but I didn't find any. 我搜索任何django库,但我找不到。 This is the most relative question I founded in SO, but it seems not helpful: 这是我在SO中创建的最相关的问题,但似乎没有帮助:

Django Javascript form validation Django Javascript表单验证

Do you know any django library for this or if not what is the best method to do this? 你知道任何django库吗?如果不知道什么是最好的方法呢?

Thanks in advance. 提前致谢。

I couldn't find any existing library to do this easily, so I use a workaround. 我找不到任何现有的库来轻松完成这项工作,所以我使用了一种解决方法。

Django form errors are in list format. Django表单错误采用列表格式。 Its difficult to transfer a list of dict from Django to JS. 很难将Django的dict列表转移到JS。 I have a function that comes in handy. 我有一个派上用场的功能。 This function (convertErrorsToDict) concatenates all errors per parameter together into 1 error.: 此函数(convertErrorsToDict)将每个参数的所有错误连接成1个错误:

views.py: views.py:

def convertErrorsToDict(errors): #previously errors={f1:[er1]}. make it {f1:'er1'} so we can render nicely
    #converts form errors from list to dictionary
    errors2={}
    for f in errors:
        errors2[f]='.'.join(errors[f])
    return (errors2)


def setPassword(request):
    your_form=FormName();
    context={}
    errors=convertErrorsToDict(your_form.errors)
    context['errors']=errors;
    return render(request,'htmlFileName.html',context)

FileName.html: FileName.html:

{% load jsonify %}
<script type="text/javascript">
    var errors={{errors|jsonify}};    
</script>

FileName.js In js file we can now directly use errors as a variable. FileName.js在js文件中,我们现在可以直接将errors用作变量。

console.log(errors.para1) //para1 is first para in the form. eg first_name
console.log(errors.para2) 

This feature is useful when we need complete control on form errors content. 当我们需要完全控制表单错误内容时,此功能非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM