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

Django表单向导-如何在多对多字段中保存选定项,django,django-models,manytomanyfield,django-formwizard,django-formtools,Django,Django Models,Manytomanyfield,Django Formwizard,Django Formtools,因此,我使用Django formtools表单向导将表单分为两个步骤。表单正在工作,数据正在保存,但许多字段项除外 用户可以创建一个可以通过标签过滤的广告。标签模型通过manytomanyfield与广告模型相关,但是在保存表单时,所选标签不会保存在广告模型中 models.py views.py 所以我想我仍然需要在AdWizardView的done方法中处理manytomy关系。我看到了答案,但解决方案抛出了一个错误 “odict_值”对象不支持索引 有人知道我错过了什么吗 致以最良好的祝

因此,我使用Django formtools表单向导将表单分为两个步骤。表单正在工作,数据正在保存,但许多字段项除外

用户可以创建一个可以通过标签过滤的广告。标签模型通过manytomanyfield与广告模型相关,但是在保存表单时,所选标签不会保存在广告模型中

models.py views.py 所以我想我仍然需要在AdWizardView的done方法中处理manytomy关系。我看到了答案,但解决方案抛出了一个错误

“odict_值”对象不支持索引

有人知道我错过了什么吗

致以最良好的祝愿

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

好吧!明白了

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

views.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)
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')
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')