【问题标题】:Django Form wizard - How to save selected items in many to many fieldDjango 表单向导 - 如何在多对多字段中保存所选项目
【发布时间】:2020-05-25 03:16:07
【问题描述】:

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

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

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 方法中处理多对多关系。我看到following question 已回答,但解决方案抛出错误...

'odict_values' 对象不支持索引

有人知道我在这里缺少什么吗?

致以最诚挚的问候,

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

【问题讨论】:

    标签: django django-models manytomanyfield django-formwizard django-formtools


    【解决方案1】:

    好的!明白了!

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

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

    【讨论】:

      猜你喜欢
      • 2018-09-30
      • 2012-07-23
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 2019-08-05
      • 1970-01-01
      • 2014-02-26
      • 1970-01-01
      相关资源
      最近更新 更多