3

Actually I need a method which have same error message in javascript validation (client side) and in my django form validation (server side).

I search for any django library for this but I didn't find any. This is the most relative question I founded in SO, but it seems not helpful:

Django Javascript form validation

Do you know any django library for this or if not what is the best method to do this?

Thanks in advance.

4

1 回答 1

1

我找不到任何现有的库来轻松地做到这一点,所以我使用了一种解决方法。

Django 表单错误采用列表格式。将 dict 列表从 Django 转移到 JS 很困难。我有一个派上用场的功能。此函数(convertErrorsToDict)将每个参数的所有错误连接在一起成为 1 个错误。:

视图.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)

文件名.html:

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

FileName.js 在 js 文件中我们现在可以直接errors作为变量使用。

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

当我们需要完全控制表单错误内容时,此功能很有用。

于 2019-01-22T04:51:28.557 回答