Send Django Form as JSON via AJAX

為{幸葍}努か 提交于 2021-01-27 06:53:39

问题


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.

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 ?

Thank you in advance for your help.


回答1:


The two main things you could do are:

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

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

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,
    }

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

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




回答2:


<script>
var data = $("#form_id").serialize()
$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});
</script>

I guess... maybe... its really not clear what you are asking



来源:https://stackoverflow.com/questions/36288922/send-django-form-as-json-via-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!