django模型形式,基于ForeignKey模型中的值限制选择

时间:2012-10-25 19:15:58

标签: django django-models django-forms django-views

我有两个模型:LeagueTeamTeam具有指向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.choices模型中准确定义Team。所以我希望如此设置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))

为了使用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)])

1 个答案:

答案 0 :(得分: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=())}