DJANGO麻烦注入MultipleChoiceField初始值

时间:2016-07-22 08:46:33

标签: python django django-forms multiplechoicefield

我有一个表单,点击按钮" info"从表中,我获取用户信息并注入表单,所有这些都可以,但不适用于 MultipleChoiceField

data = {'name': name_surname[0], 'surname': name_surname[1], 'c02': retrieved.c02, 'dep': retrieved.dept_no,
                'job': retrieved.job_code, 'location': retrieved.c03, 'fbd_role': retrieved.c04, 'team_id': TEAM_ID_RETRIEVED} 
        form = RegForm(initial=data)
        form.set_readonly()    
        return render(request, insert_form_address,
                      {'form': form, 'action': 'info', 'pk': pk, 'profiles': profile_list})

这是我的视图代码,我用来填充表单的用户值,每个字段都使用初始值正确评估,但不是最后一个,team_id。

填充team_id字段的数据示例是(这是在表单中声明的​​默认列表):

TEAM_ID = {('POCM_A09', 'POCM_A09'),
           ('POCM_A11', 'POCM_A11'),
           ('POCM_A13', 'POCM_A13'),
           ('POCM_A15', 'POCM_A15'),
           ('POCM_A16', 'POCM_A16'),
           ('POCM_A18', 'POCM_A18')}

并且假设我想用一些值来启动它,那些与该用户相关的值(这个列表已经传递到init模式,它不起作用,它仍然采用默认列表.. )

TEAM_ID_RETRIEVED = {('POCM_A09', 'POCM_A09')}

这是表格:

class RegForm(forms.Form):
    name = forms.CharField(label='Name', max_length=100)
    surname = forms.CharField(label='Surname', max_length=100)
    c02 = forms.CharField(label='AD ID', max_length=100)
    dep = CustomModelChoiceField(label='Department', queryset=Department.objects.all())
    fbd_role = forms.ChoiceField(label='FBD Role', choices=FBD_ROLES, initial=None)
    location = forms.ChoiceField(label='Location', choices=LOCATION, initial=None)
    job = forms.ChoiceField(label='Job', choices=JOBS)
    ## Unable to pass a initial value for this field..
    team_id= forms.MultipleChoiceField(label='Team', choices=TEAM_ID)


    action = None
    user_id = None

    def __init__(self, *args, **kwargs):
        self.user_id = kwargs.pop('pk', None)
        self.action = kwargs.pop('action', None)
        super(RegForm, self).__init__(*args, **kwargs)

    def set_readonly(self):
        for field in self.fields:
            self.fields[field].required = False
            self.fields[field].widget.attrs['disabled'] = 'disabled'

任何想法,我认为应该是容易修复的东西......但我不明白问题出在哪里......

For Tiny:

 data = {'name': name_surname[0], 'surname': name_surname[1], 'c02': retrieved.c02, 'dep': retrieved.dept_no,
            'job': retrieved.job_code, 'location': retrieved.c03, 'fbd_role': retrieved.c04, 'team_id': 'POCM_A09'}
    form = RegForm(initial=data)

它始终显示

enter image description here

谢谢! :)

1 个答案:

答案 0 :(得分:3)

您只需要设置值,例如:

initial = {
   ...
   "team_id": ['POCM_A09', ...] # list of all the values selected
   ...
}

根据我们的聊天讨论,我更新了答案。

您可以覆盖" MultipleChoiceField "的选择内部表单__init__()方法。首先将new_choices传递给表单,然后:

def __init__(self, *args, **kwargs): 
    new_choices = kwargs.pop('new_choices', None)
    super(FORM_NAME, self).__init__(*args, **kwargs) 
    ...
    self.fields['team_id'].choices = new_choices
    ...