使用django和ajax显示表单错误 [英] Display form errors with django and ajax

查看:68
本文介绍了使用django和ajax显示表单错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个联系表,用户可以通过它与我联系.我在ajax中使用django,并且如果没有错误,则可以正常工作.如果要在输入字段上方显示类似的内容,我想显示错误,不仅显示错误,还显示输入和错误.但是,由于ajax请求成功,因此它确实区分了成功 error 结果.但是我需要显示实际的表单错误.我该怎么办?非常感谢您的帮助.谢谢.

I have a contact form through which users would be able to contact me. I am using django with ajax, and it works fine if there's no error. I would like to show the errors if there's any like it displays above the input fields and not just the errors, but both the input and the errors. It does however differentiate between the success and error result, as the ajax request was successful. But I need to display the actual form errors. How do I that? Your help will be very much appreciated. Thank you.

观看次数:

def contact(request):
    if request.is_ajax() and request.POST:
        form = ContactForm(request.POST)
        if form.is_valid():
            new_contact = form.save()
            data = {
                'result': 'success',
                'message': 'Message Sent.'
            }
            return JsonResponse(data)
        else:
            data = {
                'result': 'error',
                'message': 'Form invalid',
                'form': 'oops.'
            }
            return JsonResponse(data)
    else:
        form = ContactForm()
        return render(request, 'public_contact.html', {
            'form': form
        })

js:

contact_right_form.find('#submit').on('click', function(event) {
    event.preventDefault();
    $.ajax({
        type: contact_right_form.attr('method'),
        url: '/contact/',
        data: contact_right_form.serialize(),
        dataType: 'json',
        success: function(data) {
            if ( data.result == 'success') {
                contact_right_message_sent.text(data.message);
                contact_right_message_sent.show();
            }
            else {
                contact_right_message_sent.text(data.message);
                contact_right_message_sent.show();
            }
        },
        error: function() {
            contact_right_message_sent.text('Sorry! Something went wrong.')
        }
    });
})

更新

我希望像没有ajax一样正常显示以下错误:

I would like to display the errors like the below as it normally does without ajax:

推荐答案

作为示例

django表单使用 form.errors.as_json() .假设:

django form returns errors with json format using form.errors.as_json(). assume:

{
    "sender": [
         {
           "message": "Enter a valid email address.", 
           "code": "invalid"
         }
    ],

    "subject": [
          {
            "message": "This field is required.", 
            "code": "required"
          }
    ]
}

此后,ajax得到响应(在成功:function(data){} 中.假定已经成为对象:

after that, ajax get a response (in success: function(data) {}. assume already become an object:

    data = {
    "sender": [
    {
        "message": "Enter a valid email address.", 
      "code": "invalid"
    },
    {
        "message": "Enter a .", 
      "code": "invalid"
    }
  ], 
   "subject": [
    {
        "message": "This field is required.", 
      "code": "required"
    }
  ]
};

并且您已经呈现了以前的表单,假设:

and you're already renders previous form, assume:

<input type="text" name="sender"> <br>
<input type="text" name="subject"> <br>
<button>Submit</button>

要渲染这些消息,您可以在点击事件中编写脚本:

and to render these messages, you can write scripts in the click events:

// in ajax success (event click)
if ($("input").next('p').length) $("input").nextAll('p').empty();
    for (var name in data) {
    for (var i in data[name]) {
      // object message error django
      var $input = $("input[name='"+ name +"']");
      $input.after("<p>" + data[name][i].message + "</p>");
    }
  }

模拟示例:

simulation example:

// simulation example, Data obtained from ajax response

var data = {
	"sender": [
  	{
    	"message": "Enter a valid email address.", 
      "code": "invalid"
    },
    {
    	"message": "Enter a .", 
      "code": "invalid"
    }
  ],
	"subject": [
  	{
    	"message": "This field is required.", 
      "code": "required"
    }
  ]
};

$("button").on("click", function() {
	if ($("input").next('p').length) $("input").nextAll('p').empty();
	for (var name in data) {
    for (var i in data[name]) {
      // object message error django
      var $input = $("input[name='"+ name +"']");
      $input.after("<p>" + data[name][i].message + "</p>");
    }
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="sender"> <br>
<input type="text" name="subject"> <br>
<button>Submit</button>

这篇关于使用django和ajax显示表单错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆