在视图中更改初始表单字段值(Django)

时间:2015-05-08 07:04:52

标签: python django forms set multiplechoicefield

我有三个表单字段,我希望在模板中发布表单之前修改/更改我的视图中的值 - 函数one_labeling()。第一个字段是label,我想在其中更改视图中的初始值。其次,我有两个选择字段,pos_tag和head_tags,我在MultiplechoiceFields post_tags和head_tags的视图中使用set_head_tags和set_post_tags,以便发布每个所选字段的值而不是数字,例如“NN”而不是1。我从表格中的pos_tags得到键1的值“NN”,但我想知道我是否可以在字段pos_tags和head_tags的视图中设置和修改初始变量,就像字段标签一样。

in forms.py

class LabelingForm(forms.ModelForm):

    label = forms.CharField(widget=forms.HiddenInput(), initial="trytrytry22",required=False)

      POS_nodes = (('1','NN'),

          ('2','POSS'),
          ....

        )
pos_tags = forms.MultipleChoiceField(choices=POS_nodes, required=False)



Head_node_choices = (('1','NP'),

          ('2','VP'),
          ...


        )


head_tags = forms.MultipleChoiceField(choices=Head_node_choices,required=False)

 class Meta:
        model = OneLabeling
        fields = ('label', 'sentence' )


    def set_head_tags(self, head_tags):
        data = self.data.copy()
        data['head_tags'] = head_tags
        self.data = data

    def set_pos_tags(self, pos_tags):
        data = self.data.copy()
        data['pos_tags'] = pos_tags
        self.data = data
在views.py中

def one_labeling(request, postID):
                form = LabelingForm(request.POST) 
                data1 =  form.cleaned_data['pos_tags']
                data2 =  form.cleaned_data['head_tags']
                if form.is_valid():
                 if data1 and data2:
                    l = data1[0]
                    ll = data2[0]
                    pos_tags = dict(form.fields['pos_tags'].choices)
                    head_tags = dict(form.fields['head_tags'].choices)
                    i = pos_tags.get(l)
                    j = head_tags.get(ll)

                    form.set_head_tags(j)
                    form.set_pos_tags(i)


                    post_one_labeling(request, one_labeling)

1 个答案:

答案 0 :(得分:0)

要为多选字段提供初始值,您可以尝试执行以下操作: -

    pos_tags = forms.MultipleChoiceField(choices=POS_nodes,
                     initial=[POS_node[0] for POS_node in POS_nodes])