我有两个模型:League
和Team
。 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.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.id
,league.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)])
答案 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=())}