【问题标题】:how to serialize list of form object to JSON in django如何在 Django 中将表单对象列表序列化为 JSON
【发布时间】:2020-05-30 15:15:39
【问题描述】:

我正在尝试序列化表单对象并返回到 AJAX 调用,以便我可以在模板中显示它们,但是我无法序列化它们,这与序列化模型对象不同,我们没有选项吗?表单对象

if request.method == 'POST':

    temp_data_form = TemplateDataForm(request.POST)

    if request.POST.get('temp_id'):
        # getting id of the current template 
        existing_template = Template.objects.filter(id=request.POST.get('temp_id'))[0]
        if request.POST.get('item'):
            item_query = existing_template.tempdata_set.filter(item=request.POST.get('item'))
            if item_query:
                item_query = item_query[0] and True

        # we only edit the existing object of the template always as we create the object by default on GET request
        if existing_template and existing_template.title != request.POST.get('title') and request.POST.get('title')!= None:
            existing_template.title = request.POST.get('title')
            existing_template.save()
        if temp_data_form.is_valid() and item_query != True:

        # Template items alias data
        td_obj = temp_data_form.save(commit=False)
        td_obj.template = existing_template
        td_obj.save()

        values_form = []

        for item in existing_template.tempdata_set.all():
            values_form.append(TemplateDataForm(instance=item))

        return JsonResponse(values_form, safe=False)

我收到以下错误。

     raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type TemplateDataForm is not JSON serializable

【问题讨论】:

  • 表单用于验证数据,是它们自己的对象。您想序列化表单中的cleaned_data,而不是表单对象。
  • @MattGleason - 我想在保存在 DB 中的模板中显示现有表单数据,以便用户在需要时更新数据,你能建议我这样做吗通过 Ajax

标签: python json django forms serialization


【解决方案1】:

假设您的 TemplateDataForm 是一个 Django 表单,它应该有一个“cleaned_data”属性。您需要序列化该数据而不是表单本身。所以对于一个单一的形式,它看起来像下面。此外,cleaned_data 是一个字典,因此您可以删除“safe=False”参数。

return JsonResponse(values_form.cleaned_data, safe=False)

但是,根据您的代码,您似乎正在尝试遍历子对象集或多个表单。因此,为此,您可能希望在循环中预先构建 json 字典响应。

json_response_dict = {}
for item in existing_template.tempdata_set.all():
        values_form.append(TemplateDataForm(instance=item))
        # Add to your response dictionary here.  Assuming you are using
        # django forms and each one is a valid form.  Your key will
        # need to be unique for each loop, so replace 'key' with a
        # loop counter such as 'form' + counter or maybe a form instance
        # cleaned_data pk.  If looping through child set objects, then
        # reference the appropriate attribute such as values_form.title.
        json_response_dict['key'] = values_form.cleaned_data

    return JsonResponse(json_response_dict, safe=False)

然后在 javascript 中,为了您的响应,您需要访问每个键。

$.ajax({
        method: 'POST',
        url: yourURL,
        data: yourData
    }).always(function (response) {
        /* Test viewing the title for a single object in dictionary.  Otherwise, loop
         * through the response in each dictionary subset to get the keys/values.
         */
        alert(response.title);
    });

【讨论】:

    猜你喜欢
    • 2019-05-17
    • 1970-01-01
    • 2012-10-13
    • 2016-12-22
    • 2022-01-19
    • 2011-09-13
    • 2017-03-07
    • 1970-01-01
    • 2017-06-10
    相关资源
    最近更新 更多