2

我想要预先选中的复选框,我通过了“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)

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

4

2 回答 2

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
于 2012-04-30T10:44:32.290 回答
0

我在下面尝试过并且有效:

self.fields['menu_%d' % item.id] = forms.BooleanField(label=item.title, required=False)
self.fields['menu_%d' % item.id].widget.attrs['checked'] = 'checked'
于 2012-05-02T03:43:27.410 回答