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

1 Answer 1

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=())}
Sign up to request clarification or add additional context in comments.

6 Comments

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 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.
You were very close! It worked after I added the following line to class Meta: widgets = {'draft_position': Select(choices=())}
@Cole Well that's good news! I'll revise the code to reflect what you said.
The problem is now that team.name is set to the league name for some reason, and the form doesn't validate.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.