2

I have two models: League and Team. Team has a foreign key link to League. I want to be able to set choices available for the Team based on values stored in League. Specifically:

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(?????????)])

I recognize I cannot accurately define my draft_slot.choices in the Team model. So I would expect to set up Team like so:

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

I have set up a ModelForm of Team:

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

And a view of the 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))

What foo do I need in order to use league.id, league.number_of_teams so the view of TeamModelForm prepopulates team.league and also renders a field to represent team.draft_slot to look like

draft_slot = models.IntegerField(choices=[(i+1,i+1) for i in range(league.number_of_teams+1)])
phoenix
  • 7,988
  • 6
  • 39
  • 45
Cole
  • 2,489
  • 1
  • 29
  • 48

1 Answers1

3

the working answer:

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=())}
rantanplan
  • 7,283
  • 1
  • 24
  • 45
  • I carefully stepped through the code. If I set n = self.instance.league.number of teams, I get a number I can iterate over. The self.fields.['draft_slot'].choices fails. I have tried to set it equal to 1, to (1,1) to ((1,1),) as well as the given code. The code fails to provide the classic drop down list of choices when TeamModelForm is viewed. Everything else looks great. – Cole Oct 25 '12 at 20:07
  • @cole See the refined code above. Notice the `self.fields['draft_slot'].widget.choices`, instead of `self.fields['draft_slot'].choices`. Tell me if it works. – rantanplan Oct 25 '12 at 20:17
  • You were very close! It worked after I added the following line to class Meta: widgets = {'draft_position': Select(choices=())} – Cole Oct 25 '12 at 20:41
  • @Cole Well that's good news! I'll revise the code to reflect what you said. – rantanplan Oct 25 '12 at 20:44
  • The problem is now that team.name is set to the league name for some reason, and the form doesn't validate. – Cole Oct 25 '12 at 20:57
  • @Cole there is no `name` field on your models. – rantanplan Oct 25 '12 at 20:58