1
我正在嘗試編制一個應該與現有值一起使用的表單。儘管我預先填充所有字段,但外鍵字段給我一個問題。從數據庫中預先填充formset_factory來自db
這裏是我的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。
我該如何糾正這種情況?
//鼠標
問題依然存在,要麼,我可以有一個模型表單集。 ..它包含了PlayerShortlist中的所有對象,而不是我想要的那些..如果PlayerShortlist首先應用了一個查詢集,那麼該字段不會得到popu遲來。 – debuggerpk 2012-04-05 19:14:47
然後嘗試在表單的'\ _ \ _ init \ _ \ _'中限制'self.fields ['player']。queryset'。另外,在BowlingDetail中是否存在一個'Player'字段,這個字符串是'PlayerShortlist'的ForeignKey? – ilvar 2012-04-06 05:48:53