我正在尝试过滤表单选择,以便用户只能从某些比赛中选择玩家。我已经更改了表单中的_init_
函数,但没有任何更改
forms.py
from django.forms import ModelForm
from matchdaycentremodel.models import FantasyTeam
from playerteamstats.models import Player
class FantasySeasonForm(ModelForm):
class Meta:
model = FantasyTeam
def _init_(self,*args,**kwargs):
super(FantasySeasonForm,self)._init_(**kwargs)
self.fields['player1'].queryset = playerteamstats.models.Player.objects.filter(team__competition__pk=2)
相关模型是......
models.py (playerteamstats)
class Competition(models.Model):
COMP_ID = models.AutoField(primary_key=True)
season = models.ForeignKey(Season) #Foreign Key
competition_id = models.IntegerField()
competition_name = models.CharField(max_length=200)
competition_code = models.CharField(max_length=6)
def __str__(self):
return '%s (%s)' % (self.competition_name, self.season.season_id) #e.g. 'English Barclays Premier League (2014)'
class Team(models.Model):
team_id = models.IntegerField(primary_key=True)
competition = models.ForeignKey(Competition) #Foreign Key
team_name = models.CharField(max_length=200)
def __str__(self):
return self.team_name
class Player(models.Model):
player_id = models.IntegerField(primary_key=True)
team = models.ForeignKey(Team) #Foreign Key
player_name = models.CharField(max_length=140)
def __str__(self):
return self.player_name
models.py (matchdaycentremodel)
class FantasyTeam(models.Model):
FANTASY_TEAM_ID = models.AutoField(primary_key=True)
player1 = models.ForeignKey(Player, related_name='player1')
player2 = models.ForeignKey(Player, related_name='player2')
player3 = models.ForeignKey(Player, related_name='player3')
views.py
@login_required
def entry(request):
fantasyTeamForm = FantasySeasonForm() #Form to store each player in the fantasy team
if request.method == 'POST':
fantasyTeamForm = FantasySeasonForm(request.POST or None)
fantasyTeamForm.fields
if fantasyTeamForm.is_valid():
fantasyTeamForm.save()
return HttpResponseRedirect('/season/entrysuccess') #page on success
args = {}
args.update(csrf(request))
args['form'] = fantasyTeamForm
return render_to_response('entry.html', args, context_instance=RequestContext(request))
如何过滤表单的播放器1,以便只能从某个竞赛中选择?
答案 0 :(得分:1)
如果您的导入声明正确,应该
self.fields['player1'].queryset = playerteamstats.models.Player.objects.filter(team__competition__pk=2)
不是
self.fields['player1'].queryset = Player.objects.filter(team__competition__pk=2)
答案 1 :(得分:1)
您的init
定义为def _init_
,而它应为def __init__
(双下划线)
另外,正如crhodes所提到的,你应该做的事情如下:
self.fields['player1'].queryset = Player.objects.filter(team__competition_id=2)
这不是引发异常的原因是,这些代码行从未执行过。