[英]how to serialize list of form object to JSON in django
我正在嘗試序列化表單對象並返回到 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
假設您的 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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.