Django,使用ManyToMany将初始数据设置为formset [英] Django, set initial data to formset with ManyToMany

查看:88
本文介绍了Django,使用ManyToMany将初始数据设置为formset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用ManyToMany字段将初始数据设置为formset.

I need to set initial data to formset with ManyToMany field.

通常,当我以fomset的形式出现 no ManyToMany字段时,我通常会这样做:

Usually i'm doing like this when there is no ManyToMany field in forms of my fomset:

PersonFormSet = forms.formsets.formset_factory(NickName, can_delete=True)
init_data = [{'name':'Vasya pupkin','nick':'Vasya'}, 
             {'name':'Vasyapupkin','nick':'Petya'}]

nick_formset = PersonFormSet(initial=init_data)

但是现在我需要设置ManyToMany字段的初始数据并尝试执行以下操作:

But now I need to set ManyToMany field initial data and tried something like this:

NickNameFormSet = forms.formsets.formset_factory(NickName, can_delete=True)
init_data = [{'name': 'Vasya Pupkin',
              'nick': {'Vasya':'selected',
                       'Petya':'notselected'}}]

nick_formset = NickNameFormSet(initial=init_data)

但这是行不通的.

如何将初始数据传递给Formset,以便它像这样呈现我的小部件:

How can I pass initial data to Formset so it render my widget like this:

<select multiple="multiple" name="person_set-0-nickname" id="id_person_set-0-nickname">
    <option value="1" selected="selected">Vasya</option>
    <option value="2">Petya</option>
</select>

注意:我只使用Forms和Django Formsets.没有Django模型.我实际上可以定义它,但是它是空的,我正在使用NoSQL.

Note: I'm using only Forms, and Formsets of Django. There is no Django models. I can actually define it but it's empty, I'm using NoSQL.

推荐答案

您应该提供pk的列表作为ManyToMany关系的初始数据,而不是dict.

You should provide a list of pk as initial data for your ManyToMany relation instead of a dict.

看看该线程,它可能对您有帮助

Take a look at this thread, it might helps you.

这篇关于Django,使用ManyToMany将初始数据设置为formset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆