通过AJAX将Django表单作为JSON发送 [英] Send Django Form as JSON via AJAX

查看:65
本文介绍了通过AJAX将Django表单作为JSON发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django 1.8.8开发项目,我需要将Django表单转换为JSON格式,以便可以通过AJAX调用将其发送到浏览器.

I am working on project in Django 1.8.8 and I need to convert a django form into a JSON format so I can send it to the browser via an AJAX call.

我找到了此软件包( https://github.com/WiserTogether/django-remote-forms )在Pypi上不再可用.自上次提交以来已经2年了.

I found this package ( https://github.com/WiserTogether/django-remote-forms ) which is no more available on Pypi. Beside it's 2 years old since the last commit.

请问我应该怎么做或使用哪个软件包?

Would you please give me some advice on what to do or which package to use ?

预先感谢您的帮助.

推荐答案

您可以做的两件事是:

  • 将表单呈现为HTML字符串,并将其发送.

  • Render the form to an HTML string, and send that.

创建一个JSON对象,可以从该对象构造HTML.

Create a JSON object, from which the HTML can be constructed.

这是一个如何将表单对象转换为json的示例:

Here's an example of how you could turn a form object into json:

import json
def form_to_json(form):
    result = {}
    for name, field in form.fields.iteritems():
        result[name] = field_to_dict(field)
    return json.dumps(result)

def field_to_dict(field):
    return {
        "type": field.__class__.__name__,
        "widget_type": field.widget.__class__.__name__,
        "hidden": field.widget.is_hidden,
        "required": field.widget.is_required,
        "label": field.label,
        "help_text": field.help_text,
        "min_length": field.min_length, # optional
        "max_length": field.max_length, # optional
        "initial_value": field.initial,
    }

如果您还想在服务器端处理错误消息,则可能还应该在field_to_dict中包含该信息.

If you also want to handle error messages server side, you should probably include that information in field_to_dict as well.

要将表单呈现为html,只需将其转换为字符串即可.

To render a form as html, just convert it to a string.

这篇关于通过AJAX将Django表单作为JSON发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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