Django 表单向导 - 如何在多对多字段中保存所选项目



所以我使用 Django formtools 表单向导将表单分为两步。表单正在工作,数据正在保存,除了多对多字段项目。

用户可以创建可按标签过滤的广告。代码模型通过多对多字段与广告模型相关,但在保存表单时,所选代码不会保存在广告模型中。

models.py

class Ad(models.Model):
title = models.CharField(max_length=200)
description = RichTextField()
tags = models.ManyToManyField('Tag')
class Tag(models.Model):
name = models.CharField(max_length=200)

views.py

FORMS = [
('title', AdCreateFormStepOne),
('tags', AdCreateFormStepTwo),
]
TEMPLATES = {
'title': 'grid/ad_form_title.html',
'tags': 'grid/ad_form_tags.html',
}
class AdWizardView(SessionWizardView):
form_list = FORMS
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def done(self, form_list, **kwargs):
instance = Ad()
for form in form_list:
instance = construct_instance(form, instance, form._meta.fields, form._meta.exclude)
instance.save()
# After the instance is saved we need to set the tags 
instance.tags.set(form.cleaned_data['tags'])
return redirect('index')

所以我想我仍然必须在 AdWizardView 的 done 方法中处理多对多关系。我看到以下问题得到了解答,但解决方案抛出了一个错误......

"odict_values"对象不支持索引

有谁知道我在这里错过了什么?

致以最诚挚的问候,

编辑:只是为了澄清,标签模型中的对象已经存在,它们使用表单上的CheckboxSelectMultiple((小部件进行选择。

好吧!知道了!

保存具有多对多关系的实例时,您无法直接保存此字段,显然您需要在保存实例后设置字段。

views.py

def done(self, form_list, **kwargs):
form_data = [form.cleaned_data for form in form_list]
instance = Ad()
for form in form_list:
instance = construct_instance(form, instance, form._meta.fields, form._meta.exclude)
instance.save()
# Select the tags from the form data and set the related tags after the instance is saved 
instance.tags.set(form_data[1]['tags'])
return redirect('index')

相关内容

最新更新