как сериализовать список объектов формы в JSON в django - PullRequest
0 голосов
/ 14 февраля 2020

Я пытаюсь сериализовать объекты формы и вернуться к вызову 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

1 Ответ

0 голосов
/ 16 февраля 2020

Предполагая, что TemplateDataForm является формой Django, он должен иметь атрибут "cleaned_data". Вам нужно сериализовать эти данные, а не саму форму. Так что для одной формы это будет выглядеть так, как показано ниже. Кроме того, cleaned_data - это словарь, поэтому вы можете удалить аргумент «safe = False».

return JsonResponse(values_form.cleaned_data, safe=False)

Однако, исходя из вашего кода, похоже, что вы пытаетесь провести l oop через дочерний объект установить или несколько форм. Таким образом, для этого вы, вероятно, захотите предварительно построить словарный ответ json в l oop.

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);
    });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...