简体   繁体   English

使用Ajax张贴Django表单数据时呈现验证错误

[英]Rendering validation errors when using Ajax to POST Django form data

How does one generally go about handling validation errors when using Ajax to process POST requests of Django forms? 在使用Ajax处理Django表单的POST请求时,通常如何处理验证错误?

I'm a server-side dev dabbling in a bit of pure JS to learn the ropes. 我是一个服务器端开发人员,他涉猎一些纯JS来学习绳子。 I finished writing AJAX methods to handle the POST request of a Django form, but am now unsure regarding how to render validation errors. 我已完成编写AJAX方法来处理Django表单的POST请求,但现在不确定如何呈现验证错误。

For instance, here's a simple Django form: 例如,这是一个简单的Django表单:

class TextForm(forms.Form):

    reply = forms.CharField(widget=forms.Textarea(attrs={'cols':30,'class': 'cxl','autocomplete': 'off','autofocus': 'autofocus'}))

    def __init__(self,*args,**kwargs):
        super(TextForm, self).__init__(*args,**kwargs)
        self.fields['reply'].widget.attrs['id'] = 'text_field'

    def clean(self):
        data = self.cleaned_data
        reply = data["reply"].strip()
        if not reply:
            raise forms.ValidationError('Write something')
        elif len(reply) > 1500:
            raise forms.ValidationError("Can't exceed 1500 chars")
        return reply

And here's how the Ajax request works: 这是Ajax请求的工作方式:

function overwrite_default_submit(e) {
  // block the default behavior
  e.preventDefault();

  // create and populate the form with data
  var form_data = new FormData();
  form_data.append("reply", text_field.value);

  // send the form via AJAX
  var xhr = new XMLHttpRequest();
  xhr.open('POST', e.target.action);
  xhr.setRequestHeader("X-CSRFToken", get_cookie('csrftoken'));
  xhr.send(form_data);
}

What's the best pattern to catch and display validation errors under such circumstances? 在这种情况下捕获和显示验证错误的最佳模式是什么? Moreover, what if a file upload field was involved? 此外,如果涉及文件上载字段怎么办? Would love to see an illustrative example of how the experts do it. 希望看到专家们如何做的一个说明性例子。

Note: I prefer pure JS at this point since that's what I'm starting with. 注意:由于我是从这里开始的,因此我现在更喜欢纯JS。 JQuery's on my radar, but I'll look at it in the future. JQuery备受关注,但以后会介绍。

In the Django view, at the point where form.is_valid() fails, one can further place a check of the sort if request.is_ajax() . 在Django视图中,在form.is_valid()失败的地方, if request.is_ajax()可以进一步检查排序。 In this block, an HTTPResponse (or JSONResponse) of the following structure can be returned: 在此块中,可以返回以下结构的HTTPResponse(或JSONResponse):

payload = {}
payload['success'] = False
payload['message'] = ERR_MSG['generic']
return HttpResponse(json.dumps(payload),content_type='application/json',)

This, in turn, can be caught in the AJAX side of things like so: 反过来,这可以陷入AJAX方面,例如:

  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200)
        {
            var resp = JSON.parse(this.responseText);
            if (!resp.success) {
                console.log(resp.message);
            } else {
                console.log("success at last");
            }
        }
    }; 

Once the payload has reached the realm of JS, one can then proceed to render it accordingly. 一旦有效负载到达JS领域,就可以进行相应的渲染。

I'll add more sophistication to this answer when/if I discover more (and when warranted). 当/如果我发现更多(且必要时),我将在此答案中添加更复杂的内容。 Over and out. 完了,走吧。

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

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