在我的记分卡报名表上,我只希望用户从列入名单的球员中选择该比赛。如果有一个字段,我就可以成功地使用。
form.fields['player'].queryset = PlayerShortlist.objects.filter(team=userteam, fixture=fixture_id)
但是当我在formset_factory上应用它时,我无法获得结果。
my forms.py
class TossForm(forms.Form):
toss_won_by = forms.BooleanField()
bat_first = forms.BooleanField()
class InningsForm(forms.Form):
player = forms.ModelChoiceField(
PlayerShortlist.objects.all()
)
status = forms.ChoiceField(choices=OUT_CHOICES, initial='DNB')
score = forms.IntegerField(initial=0)
balls_faced = forms.IntegerField(initial=0)
my views.py
@login_required
def scorecard(request, team_id, fixture_id):
template = get_template('cricket/scorecard.html')
tossform = TossForm()
#inningform = InningsForm()
InningsForms = formset_factory(InningsForm, extra=11)
inningsforms = InningsForm()
inningsforms.fields['player'].queryset = PlayerShortlist.objects.filter(team=Team.objects.get(id=1), fixture=fixture_id)
page_vars = Context({
'loggedinuser': request.user,
'tossform': tossform,
'inningsforms': inningsforms,
})
crsfcontext = RequestContext(request, page_vars)
output = template.render(crsfcontext)
return HttpResponse(output)
它给了我错误。
'InningsFormFormSet'对象没有属性'fields'
感谢
//优素福
哦,我环顾四周,看来formfield_callback可以用于我想要的东西,但是当我使用它时,我的views.py就像def update_field(field, **kwargs):
if field.name == 'players':
field.queryset = PlayerShortlist.objects.filter(team=Team.objects.get(id=team_id), fixture=fixture_id)
InningsFormset = formset_factory(InningsForm, extra=11, formfield_callback)
它给了我
formset_factory()得到了一个意外的关键字参数'formfield_callback'
答案 0 :(得分:1)
请记住:表单集包含表单列表。所以这个:
inningsforms.fields['player'].queryset = PlayerShortlist.objects.filter(team=Team.objects.get(id=1), fixture=fixture_id)
应该是:
qs = PlayerShortlist.objects.filter(team=Team.objects.get(id=1), fixture=fixture_id)
# force execution of the queryset once and for all
list(qs)
for form in inningsforms.forms:
form.fields['player'].queryset = qs
另外,formfield_callback是modelformset_factory(和modelform_factory)的参数,而不是formset_factory。看看它是如何使用的:
def modelformset_factory(model, form=ModelForm, formfield_callback=None,
formset=BaseModelFormSet,
extra=1, can_delete=False, can_order=False,
max_num=None, fields=None, exclude=None):
"""
Returns a FormSet class for the given Django model class.
"""
form = modelform_factory(model, form=form, fields=fields, exclude=exclude,
formfield_callback=formfield_callback)
FormSet = formset_factory(form, formset, extra=extra, max_num=max_num,
can_order=can_order, can_delete=can_delete)
FormSet.model = model
return FormSet
请参阅,formfield_callback由modelformset_factory代理到modelform_factory。