如何在Django中将表单对象列表序列化为JSON [英] how to serialize list of form object to JSON in django

查看:149
本文介绍了如何在Django中将表单对象列表序列化为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to serialize the form objects and return to the AJAX call so that I can display them in the template, but I'm not able to serialize them unlike serializing the model objects don't we have an option for form objects

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

推荐答案

假设您的TemplateDataForm是Django表单,则应具有"cleaned_data"属性.您需要序列化该数据,而不是表格本身.因此,对于单个表格,将如下所示.另外,cleaned_data是一个字典,因此您可以删除"safe = False"参数.

Assuming your TemplateDataForm is a Django form, it should have a "cleaned_data" attribute. You need to serialize that data and not the form itself. So for a single form, that would look like the below. Also, cleaned_data is a dictionary, so you can drop the "safe=False" argument.

return JsonResponse(values_form.cleaned_data, safe=False)

但是,根据您的代码,您似乎试图遍历子对象集或多种形式.因此,为此,您可能需要在循环中预先构建json字典响应.

However, based on your code, it looks like you are trying to loop through a child object set or multiple forms. So, for that, you would probably want to pre-build the json dictionary response in the loop.

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中,您需要访问每个键才能获得响应.

Then in javascript, for your response, you would need to access each key.

$.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);
    });

这篇关于如何在Django中将表单对象列表序列化为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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