1

我正在尝试制作一个应该使用现有值进行推广的编辑表单。虽然我预先填充了所有字段,但是外键字段给了我一个问题。

这是我的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)

它正确地给了我所有的值,除了外键字段。t 进一步调查我继续并打印了 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。

我该如何纠正这种情况?

//鼠

4

1 回答 1

1

使用ModelForminstance(或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)
于 2012-04-05T04:10:06.247 回答