如何在Django和AJAX中正确显示ValidationError?

时间:2017-11-02 13:00:37

标签: javascript jquery python ajax django

在我的Django项目中,我有一个表单模式,超级用户可以创建新用户。

我想显示我在ValidationError文件中设置的forms.py,当超级用户误写现有的电子邮件或密码不相似时。

正确的是,当超级用户提交有错误的表单时,如上所述浏览器引发错误:

SyntaxError: JSON.parse: unexpected character at line 3 column 1 of the JSON data

Uncaught TypeError: a.replace is not a function
    at Function.htmlPrefilter (jquery.min.js:3)
    at qa (jquery.min.js:3)
    at Ja (jquery.min.js:3)
    at r.fn.init.append (jquery.min.js:3)
    at r.fn.init.<anonymous> (jquery.min.js:3)
    at T (jquery.min.js:3)
    at r.fn.init.html (jquery.min.js:3)
    at Object.error (crud.js:45)
    at i (jquery.min.js:2)
    at Object.fireWith [as rejectWith] (jquery.min.js:2)

问题:如何在数据无效时正确显示错误消息?

forms.py:

class UserCreateForm(UserCreationForm):
    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'is_active', 'is_superuser', 'password1', 'password2')

    def clean_email(self):
        email = self.cleaned_data['email']
        if User.objects.filter(email=email).exists():
            raise ValidationError(_("Email already exists."))
        return email

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(_("Enter the same password as above, for verification."))
        return password2

views.py:

class UserCreateView(CreateView):
    template_name = 'users/create_user.html'
    form_class = UserCreateForm

    def get(self, request, *args, **kwargs):
        data = dict()
        user_create_form = UserCreateForm()
        context = {'user_create_form': user_create_form}
        data['html_user_create_form'] = render_to_string(
            'users/create_user.html', context, request=request
        )
        return JsonResponse(data)

    def form_valid(self, form):
        form.save()
        data = dict()
        data['form_is_valid'] = True
        context = {'profiles': Profile.objects.all(),}
        data['html_users'] = render_to_string('users/users.html', context)
        return JsonResponse(data)

JS:

$(function ($) {
    $("#userModalBox").on("submit", ".userCreateForm", function () {
        var form = $(this);
        var dataForm = new FormData(form.get(0));
        $.ajax({
            url: form.attr("action"),
            data: dataForm,
            type: form.attr("method"),
            dataType: 'json',
            success: function (data) {
                if (data.form_is_valid) {
                    $("#loader").show("slow");
                    setTimeout(function() {
                        $("#loader").hide("slow");
                        $("#users").html(data.html_users);
                        $("#users").sortable("refresh");
                        $("#users").sortable("option", "disabled", $("#users .list-group-item").length == 1);
                        $("#userModalBox").modal("hide");
                        $("#userMessageCreate").fadeIn("slow");
                        setTimeout(function() {$("#userMessageCreate").fadeOut("slow");}, 2000);
                        $('#searchUsers').val('');
                    }, 2500);
                }
                else {
                    $("#userModalBox .modal-content").html(data.html_user_create_form);
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                $("#userError").fadeIn("slow")
                $("#userError span.error-description").html(thrownError);
                setTimeout(function() {$("#userError").fadeOut("slow");}, 10000);
            },
            cache: false,
            contentType: false,
            processData: false
        });
        return false;
    });
}(jQuery));

模板:

{# START: AJAX ERROR #}
<div class="alert alert-danger alert-dismissible text-center" role="alert" id="userError">
     <i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
    <strong>&nbsp;{% trans "ERROR" %}:</strong><br><span class="error-description"></span>
</div>
{# END: AJAX ERROR #}


{# START: DJANGO ERROR #}
{% if user_create_form.non_field_errors %}
  <div class="well well-error">
    {% for error in user_create_form.non_field_errors %}
      <ul class="list-unstyled">
        <li class="text-danger">
          <i class="fa fa-exclamation-circle" aria-hidden="true"></i>
            <strong>&nbsp;{{ error|escape }}</strong>
          </li>
        </ul>
    {% endfor %}
  </div>
{% endif %}
{# END: DJANGO ERROR #}

编辑部分:

views.py:

def form_invalid(self, form):
        data = dict()
        data['form_is_valid'] = False
        data['form_errors'] = form.errors
        print form.errors
        return JsonResponse(data)

JS:

if (data.form_is_valid) {
   // Some code             
}
else {
   $("#userModalBox .modal-content").html(data.html_user_create_form);
   $('#userModalBox .error-description').html(data.form_errors); <-- DONT WORK???
}

2 个答案:

答案 0 :(得分:2)

仅当表单有效时才会调用

form_valid,因此名称为。

因此,在您的表单有效的情况下,您将返回JSON响应,正如您的JS代码所期望的那样。但是,如果表单无效,Django将调用form_invalid;并且由于您没有覆盖该方法,它将继续返回纯HTML响应。

答案 1 :(得分:2)

如果要在AJAX响应中返回表单错误,

像这样覆盖form_invalid:

def form_invalid(self, form):
    error_dict= {'status':'form-invalid','form-errors':form.errors}
    return HttpResponse(json.dumps(error_dict),content_type="application/json")

form.errors:如果password1!= password2,则获取表单验证错误。 在你的ajax成功响应中(“表单有效且无效将始终返回响应,只有当代码在表单中有效时,错误函数才会起作用”)

在你的AJAX中:

if (data.status=="form-invalid") {
    Whatever you want to do e.g. 
    $('.class-name').html(data.form-errors)
}

data.status检查响应中返回的json-dict是否有status =“form-errors”,然后将这些错误附加到div或任何你想要的地方。

注意:只有在没有对请求的响应时,Ajax错误功能才有效。表单有效且无效将始终返回响应,并且将进入ajax成功函数,除非代码中出现中断/错误(将不返回任何响应)。