如何隐藏modelformset_factory生成的输入中的所有标签?

时间:2016-11-02 15:49:08

标签: python django

我在forms.py

中有以下代码
class MCQuestionForm(forms.ModelForm):

    class Meta:
        model = models.MultipleChoiceQuestion
        fields = ('prompt',)

    def __init__(self, *args, **kwargs):
        super(MCQuestionForm, self).__init__(*args, **kwargs)        
        self.fields['choice'] = forms.ModelChoiceField(queryset=self.instance.choice.all(),
                                                   widget=forms.RadioSelect,
                                                   empty_label=None)


MCQuestionFormSetForUser = modelformset_factory(models.MultipleChoiceQuestion,
                                            fields=('prompt',),
                                            form=MCQuestionForm,
                                            extra=0,
                                            widgets={
                                                'prompt': forms.TextInput(
                                                    attrs={'readonly': True, 'class': 'borderless'})
                                            }
                                            )

当我放置" MCQuestionFormSetForUser"如模板中的formset.as_p,提示字段和选项都会获得相应的标签。我该如何隐藏它们?

1 个答案:

答案 0 :(得分:0)

找到了做到这一点的方法

class MCQuestionForm(forms.ModelForm):

    class Meta:
        model = models.MultipleChoiceQuestion
        fields = ('prompt',)

        def __init__(self, *args, **kwargs):
            super(MCQuestionForm, self).__init__(*args, **kwargs)
            self.fields['choice'] = forms.ModelChoiceField(queryset=self.instance.choice.all(),
                                                   widget=forms.RadioSelect,
                                                   empty_label=None)

            # here is the override that I was looking for
            self.fields['choice'].label = ''
            self.fields['prompt'].label = ''