2

我有两个模型:LeagueTeam. Team有一个外键链接到League. 我希望能够Team根据存储在League. 具体来说:

class League(models.Model):
    number_of_teams = models.IntegerField()

class Team(models.Model):
    league = models.ForeignKey(League)
    draft_slot = models.IntegerField(choices=[(i+1,i+1) for i in range(?????????)])

我认识到我无法draft_slot.choicesTeam模型中准确定义我的。所以我希望这样设置Team

class Team(models.Model):
    league = models.ForeignKey(League)
    draft_slot = models.IntegerField()

我已经设置了ModelForm一个Team

class TeamModelForm(ModelForm):
    class Meta:
        model = Team

并查看Team ModelForm

def SetupTeam(request, fanatic_slug=None, league_slug=None):
    league = League.objects.get(slug=league_slug)
    form = TeamModelForm()
    return render_to_response('league/addteam.html', {
        'form': form
    }, context_instance = RequestContext(request))

我需要什么 foo 才能使用league.idleague.number_of_teams所以TeamModelForm预填充视图team.league并呈现一个字段来表示team.draft_slot看起来像

draft_slot = models.IntegerField(choices=[(i+1,i+1) for i in range(league.number_of_teams+1)])
4

1 回答 1

3

工作答案:

class TeamModelForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(TeamModelForm, self).__init__(*args, **kwargs)
        if self.instance:
            n = self.instance.number_of_teams
            self.fields['draft_position'].widget.choices = [(i+1,i+1) for i in range(n)]

    class Meta:
        model = Team
        widgets = {'draft_position': Select(choices=())}
于 2012-10-25T19:44:35.173 回答