0

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

用户可以创建一个可以按标签过滤的广告。Tag 模型通过多字段关联到 Ad 模型,但是在保存表单时,选定的标签不会保存在 Ad 模型中。

模型.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)

视图.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() 小部件进行了选择。

4

1 回答 1

0

好吧!知道了!

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

视图.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')
于 2020-02-10T09:17:49.160 回答