在Django中返回AJAX请求的表单错误 [英] Returning form errors for AJAX request in Django

查看:159
本文介绍了在Django中返回AJAX请求的表单错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在找Django和jQuery的方式。我在Django中构建了一个基本的表单。点击提交时,我使用jQuery向服务器发出一个AJAX请求来发布我的数据。这个位似乎工作正常,我设法保存数据。当表单无效时,Django返回ValidationError。有人可以告诉我如何返回这组错误消息作为对我的AJAX请求的响应,所以我可以轻松地使用JS迭代,并做任何事情。



我发现<一个href =http://www.djangosnippets.org/snippets/992/ =noreferrer>这个片段。看看JS位(processJson),你会看到他似乎通过从响应HTML中提取错误消息来获取错误消息。对我来说似乎有点笨拙。这是最好的方法吗?



我的歉意为任何模糊。



提前感谢。

解决方案

哇,这是我看过这个线程的一年。那么,随着Django 1.3的出现以及神奇的,无文档的基于类的观点,Django的视图相关功能变得更加容易。我的项目,大量使用Django的基于类的通用CRUS视图需要AJAX和JSON功能。我添加了一个例子,说明我如何修改Django的更新视图来支持AJAX并以JSON格式返回AJAX响应。看看:

  def errors_to_json(errors):

转换表单错误列表到JSON ::

return dict(
(k,map(unicode,v))
for(k,v)in errors.iteritems()


class HybridUpdateView(UpdateView):

说出JSON
的自定义更新通用视图
def form_valid(self ,形式,* args,** kwargs):

表单有效

form.save()

self.message = _(验证已过。表单保存)
self.data =无
self.success = True

有效负载= {'成功':自我。成功,'message':self.message,'data':self.data}

如果self.request.is_ajax():
返回HttpResponse(json.dumps(payload),
content_type ='application / json',

else:
return super(HybridUpdateView,self).form_valid(
form,* args,** kwargs


def form_invalid(self,form,* args,** kwargs):

表单无效

#form.save()

self.message = _(验证失败。 )
self.data = errors_to_json(form.errors)
self.success = False

payload = {'success':self.success,'message':self.message ,'data':self.data}

如果self.request.is_ajax():
返回HttpResponse(json.dumps(payload),
content_type ='application / json ',

else:
return super(HybridUpdateView,self).form_invalid(
form,* args,** kwargs

响应JSON包含三个字段 - 消息(这是一个人类可读的消息),数据(w这就是表单错误的列表)和成功(这是 true false ,分别指示请求是否成功。这在jQuery客户端很容易处理。示例响应如下所示:

 内容类型:application / json 

{message 验证失败,数据:{主机:[此字段为必需。]},成功:false}

这只是我如何将表单错误序列化到JSON并在基于类的通用视图中实现的示例,但是可以将其同步到使用常规样式视图。 p>

I've been finding my way around Django and jQuery. I've built a basic form in Django. On clicking submit, I'm using jQuery to make an AJAX request to the sever to post my data. This bit seems to work fine and I've managed to save the data. Django returns a ValidationError when a form is invalid. Could anyone tell me how to return this set of error messages as a response to my AJAX request so I can easily iterate through it using JS and do whatever?

I found this snippet. Looking at the JS bit (processJson) you'll see that he seems to get the error messages by extracting them from the response HTML. It seems kinda kludgy to me. Is this the best way to go about it?

My apologies for any vagueness.

Thanks in advance.

解决方案

Wow, it's been a year since I've seen this thread. Well, with the advent of Django 1.3 and the magical, undocumented class-based views, it's become more easy to extent Django's view related functionality. My project which makes heavy use of Django's class-based generic CRUS views need AJAX and JSON functionality. I've added an example of how I've modified Django's update view to support AJAX and return AJAX responses in the JSON format. Have a look:

def errors_to_json(errors):
    """
    Convert a Form error list to JSON::
    """
    return dict(
            (k, map(unicode, v))
            for (k,v) in errors.iteritems()
        )

class HybridUpdateView(UpdateView):
    """
    Custom update generic view that speaks JSON
    """
    def form_valid(self, form, *args, **kwargs):
        """
        The Form is valid
        """
        form.save()

        self.message = _("Validation passed. Form Saved.")
        self.data = None
        self.success = True

        payload = {'success': self.success, 'message': self.message, 'data':self.data}

        if self.request.is_ajax():
            return HttpResponse(json.dumps(payload),
                content_type='application/json',
            )
        else:
            return super(HybridUpdateView, self).form_valid(
                form, *args, **kwargs
            )

    def form_invalid(self, form, *args, **kwargs):
        """
        The Form is invalid
        """
        #form.save()

        self.message = _("Validation failed.")
        self.data = errors_to_json(form.errors)
        self.success = False

        payload = {'success': self.success, 'message': self.message, 'data':self.data}

        if self.request.is_ajax():
            return HttpResponse(json.dumps(payload),
                content_type='application/json',
            )
        else:
            return super(HybridUpdateView, self).form_invalid(
                form, *args, **kwargs
            )

The response JSON contains three fields — message (which is a human readable message), data (which is this case would be the list of form errors) and success (which is either true or false, indicating whether the request was successful or not respectively.). This is very easy to handle in jQuery client-side. A sample response looks like:

Content-Type: application/json

{"message": "Validation failed.", "data": {"host": ["This field is required."]}, "success": false}

This is just an example of how I serialized the form errors to JSON and implemented it in a class-based generic view but can be cannibalized to work with regular style views as well.

这篇关于在Django中返回AJAX请求的表单错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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