django forms.ModelChoiceField 过滤queryset中的结果
form中设置
class TotalMarkForm(forms.Form): crew_infos = forms.ModelChoiceField( queryset=models.Crew2Train.objects.all(), ) closing_date = forms.DateField() train_marks = forms.ModelChoiceField( queryset=models.TrainMark.objects.all(), label='车次', widget=forms.Select(attrs={'class': 'form-control', }) ) total = forms.FloatField( label='日进款', initial=0.0, widget=forms.NumberInput(attrs={'class': 'form-control'}) ) plan = forms.FloatField( label='日计划', initial=0.0, widget=forms.NumberInput(attrs={'class': 'form-control'}) )
想过滤点crew_infos里,当日未出现的班组
view中
if date_inquery: crew_train_formset = formset_factory(myform.TotalMarkForm, extra=m_num) total_mark_form = myform.TotalMarkForm() 在return到前端生成以前,对TotalMarkForm里的属性重新赋值, total_mark_form.fields['crew_infos'] = forms.ModelChoiceField( queryset=models.TotalMark.objects.filter(closing_date=date_inquery), initial='乘务组', label='乘务组', error_messages={ 'required': '不能为空' }, widget=forms.Select(attrs={'class': 'form-control', }), ) total_mark_form.fields['closing_date'] = forms.DateField( label='日期', initial=date_inquery, widget=forms.DateInput( attrs={ 'type': 'date', 'class': 'form-control', } ) ) total_mark_form.fields['train_marks'] = forms.ModelChoiceField( queryset=models.TotalMark.objects.filter() ) return render(request, 'total_mark_edit.html', locals())