Initial = True无法在django动态表单中工作

时间:2012-04-30 07:51:26

标签: django forms checkbox customization

我想要预先选中复选框,我传递了“initial = True”但它无效。下面是代码。

class permForm(forms.Form):

    id = forms.CharField(widget=forms.TextInput(attrs={'id':'user_id'}),required=False)

    def __init__(self, data, **kwargs):
        super(permForm, self).__init__(data, **kwargs)
        # offset_arr=data.split('/')
        # menu_id=offset_arr[1]
        # user_id=offset_arr[2]
        # flag=   offset_arr[3]
        # if user.has_perm(permission.codename, task):
        usr  = User.objects.get(id=1)
        task = Site.objects.get_current()

        for item in list(AdminMenu.objects.filter(parent_id=0)):
            permission=Permission.objects.get(id=item.permission_id);
            if usr.has_perm(permission.codename, task):
                checked=False
            else:
                checked=True
            self.fields['menu_%d' % item.id] = forms.BooleanField(initial=True,label=item.title,required=False)
            for childitem in list(AdminMenu.objects.filter(parent_id=item.id)):
                cpermission=Permission.objects.get(id=childitem.permission_id);
                if usr.has_perm(cpermission.codename, task):
                    childchecked=True
                else:
                    childchecked=False

                self.fields['menu_%s' %childitem.id] = forms.BooleanField(initial=True,label=childitem.title+'%s'%(data),required=False)

然而,它适用于静态表单。请参阅下面的代码

类MyForm(forms.Form):
     option = forms.BooleanField(required = False,initial = True)

是否有任何技巧可以为动态加载的表单元素传递初始值?

2 个答案:

答案 0 :(得分:2)

试试这个:

而不是

self.fields['menu_%d' % item.id] = forms.BooleanField(initial=True,label=item.title,required=False)

构造字段时删除initial = True参数并填充其初始值 下一步的价值如下:

self.fields['menu_%d' % item.id] = forms.BooleanField(label=item.title,required=False)
self.fields['menu_%d' % item.id].initial = True

答案 1 :(得分:0)

我在下面尝试了它的确有效:

self.fields['menu_%d' % item.id] = forms.BooleanField(label=item.title, required=False)
self.fields['menu_%d' % item.id].widget.attrs['checked'] = 'checked'