动态设置复选框的初始值 [英] Set initial value of checkbox dynamically

查看:171
本文介绍了动态设置复选框的初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  weight_training_days = forms.MultipleChoiceField(
help_text = u' (必填)必须选择3天',
widget = forms.CheckboxSelectMultiple(attrs = {
'inline':True,
}),
choices =(
(0,Mon),
(1,Tue),
(2,Wed),
(3,Thu),
4,星期五),
(5,星期六),
(6,太阳),
),

我试图将7个复选框中的3个复选框动态设置为True。理想情况下,我会从视图中执行此操作。

  def change_challenge_settings_page(请求):
$ bc = Challenge。 objects.get(user__exact = request.user,chal_status = 1)

layout ='horizo​​ntal'
form = UpdateChallengeSettingsForm(initial = {'goal':c.level_goal})

return render(request,'portal / portal_change_challenge_settings.html',{'form':form,'layout':layout,'scorecard_page':True,})

我知道如何使用ChoiceFields来做到这一点(在上面的例子中,goal是一个ChoiceField),但是当涉及到MultipleChoiceFields时,我就陷入了困境。我真的很感激任何想法/反馈。 在这种情况下,如果您设置 YourForm(inital = {'weight_training_days':[0,1,2]}),它将默认选中星期一,星期二和星期三。你也可以这样做 forms.MultipleChoiceField(... inital = [0,1,2] ...)


I have a MultipleChoiceField with a CheckboxSelectMutliple widget:

weight_training_days = forms.MultipleChoiceField(
    help_text=u'(Required) 3 days must be selected',
    widget=forms.CheckboxSelectMultiple(attrs={
        'inline': True,
    }),
    choices=(
        (0, "Mon"),
        (1, "Tue"),
        (2, "Wed"),
        (3, "Thu"),
        (4, "Fri"),
        (5, "Sat"),
        (6, "Sun"),
    ),
)

What I'm trying to is dynamically set 3 of the 7 checkboxes to "True". Ideally I would do this from the view.

def change_challenge_settings_page(request):

    c = Challenge.objects.get(user__exact = request.user,chal_status=1)

    layout = 'horizontal'
    form =UpdateChallengeSettingsForm(initial={'goal': c.level_goal }) 

    return render(request, 'portal/portal_change_challenge_settings.html', {'form': form,'layout': layout,'scorecard_page': True,})

I know how to do this with ChoiceFields (in the example above the "goal" is a ChoiceField) but am stuck when it comes to MultipleChoiceFields. I really appreciate any thoughts/feedback.

解决方案

You can set the initial to be a list. In this case if you set YourForm(inital={'weight_training_days': [0,1,2]}) it will default to having Monday, Tuesday and Wednesday selected. You can also do it like so forms.MultipleChoiceField(... inital=[0,1,2] ...)

这篇关于动态设置复选框的初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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