我想要预先选中的复选框,我通过了“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)
是否有任何技巧可以为动态加载的表单元素传递初始值?