如何在Django表单ModelChoiceField中设置初始

时间:2019-06-06 06:30:48

标签: django python-3.x

我正在尝试为 ModelChoiceField 设置初始值,但未设置

我尝试设置初始字母,但也没有帮助

self.fields['query'].initial = Queries.objects.filter(category=category, query='APPLY ALL').values('id')

实际代码:

class ChoiceForm(forms.ModelForm):

      files = forms.ModelChoiceField(queryset=Document.objects.all())
      query = forms.ModelChoiceField(queryset=Queries.objects.all(), required=False)

      class Meta:
        model = Categories
        fields = ('category','file_choice', 'files', 'query')

      def __init__(self, *args, **kwargs):
        super(ChoiceForm, self).__init__(*args, **kwargs)
        self.fields['files'].queryset = Document.objects.none()
        self.fields['query'].queryset = Queries.objects.none()

     if 'category' in self.data:
            try:
                category = (self.data.get('category'))
                self.fields['files'].queryset = Document.objects.filter(categories=category)
                self.fields['query'].queryset = Queries.objects.filter(category=category)
                self.fields['query'].initial = Queries.objects.filter(category=category, query='APPLY ALL').values('id')

设置初始值后,我在输出中一无所获。

0 个答案:

没有答案