我正在尝试制作一个应该用现有值推测的编辑表单。虽然我预先填充了所有字段,但是外键字段给我一个问题。
这是我的forms.py
def make_bowling_form(teamid, fixtureid):
class BowlingForm(forms.Form):
player = forms.ModelChoiceField(
queryset=PlayerShortlist.objects.filter(
team = teamid,
fixture = fixtureid
)
)
overs = forms.FloatField(initial=0.0)
runs = forms.IntegerField(initial=0)
wickets = forms.IntegerField(initial=0)
return BowlingForm
和views.py
@login_required
def edit_bowling(request, team_id, fixture_id):
template = get_template('cricket/edit_bowling.html')
if Team.objects.get(id=team_id) == Team.objects.get(owner=request.user):
matchscorecard = InningsCard.objects.get(team = team_id, fixture = fixture_id)
bowlers = BowlingDetail.objects.filter(innings = matchscorecard)
bowlingforms = formset_factory(
make_bowling_form(team_id, fixture_id),
extra=0,
)
bowlingforms = bowlingforms(initial = bowlers.values())
page_vars=Context({
'loggedinuser': request.user,
'bowlers': bowlers,
'bowlingforms': bowlingforms,
})
else:
error = "You dont have permission to add score for this team"
page_vars=Context({
'loggedinuser': request.user,
'error': error
})
crsfcontext = RequestContext(request, page_vars)
output = template.render(crsfcontext)
return HttpResponse(output)
除了外键字段外,它正确地给了我所有的值。进一步调查我继续并打印了bowlers.value()
[{'runs': 32, 'innings_id': 1, 'wickets': 1, 'player_id': 3, 'overs': 4.0, 'id': 1}, {'runs': 21, 'innings_id': 1, 'wickets': 3, 'player_id': 4, 'overs': 4.0, 'id': 2}, {'runs': 19, 'innings_id': 1, 'wickets': 3, 'player_id': 2, 'overs': 4.0, 'id': 3}]
我的模板给了我..
<select name="form-0-player" id="id_form-0-player">
<option value="" selected="selected">---------</option>
<option value="37">AC</option>
<option value="38">AD</option>
<option value="39">DD</option>
<option value="40">LF</option>
<option value="41">22</option>
<option value="42">dkja</option>
</select>
在这种情况下选择的值是----------- ..它应该是我选择的值,但是我的bowlers.value没有给我一个名字..它给了我一个id。
我该如何纠正这种情况?
//小鼠
答案 0 :(得分:1)
使用ModelForm
和instance
(或queryset
用于表单集):
def make_bowling_form(teamid, fixtureid):
class BowlingForm(forms.ModelForm):
class Meta:
model = Bowling
player = forms.ModelChoiceField(
queryset=PlayerShortlist.objects.filter(
team = teamid,
fixture = fixtureid
)
)
return BowlingForm
和
BowlingFormSet = modelformset_factory(
make_bowling_form(team_id, fixture_id),
extra=0,
)
bowlingforms = BowlingFormSet(queryset=bowlers)