django model form, restrict choices based on value in ForeignKey model

拈花ヽ惹草 提交于 2019-12-02 02:55:13

问题


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:


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=())}


来源:https://stackoverflow.com/questions/13075619/django-model-form-restrict-choices-based-on-value-in-foreignkey-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!