gpt4 book ai didi

Django 将自定义表单参数传递给 ModelFormset

转载 作者:行者123 更新时间:2023-12-01 00:06:28 27 4
gpt4 key购买 nike

我的问题类似于 Django Passing Custom Form Parameters to Formset

我有这些课

class Game(models.Model):
home_team = models.ForeignKey(Team, related_name='home_team')
away_team = models.ForeignKey(Team, related_name='away_team')
round = models.ForeignKey(Round)

TEAM_CHOICES = ((1, '1'), (2, 'X'), (3, '2'),)

class Odds(models.Model):
game = models.ForeignKey(Game, unique=False)
team = models.IntegerField(choices = TEAM_CHOICES)
odds = models.FloatField()
class Meta:
verbose_name_plural = "Odds"
unique_together = (
("game", "team"),
)

class Vote(models.Model):
user = models.ForeignKey(User, unique=False)
game = models.ForeignKey(Game)
score = models.ForeignKey(Odds)
class Meta:
unique_together = (
("game", "user"),)

我已经定义了我自己的modelformset_factory:
def mymodelformset_factory(ins):
class VoteForm(forms.ModelForm):
score = forms.ModelChoiceField(queryset=Odds.objects.filter(game=ins), widget=forms.RadioSelect(), empty_label=None)
def __init__(self, *args, **kwargs):
super(VoteForm, self).__init__(*args, **kwargs)
class Meta:
model = Vote
exclude = ['user']
return VoteForm

我像这样使用它:
        VoteFormSet = modelformset_factory(Vote, form=mymodelformset_factory(v), extra=0)
formset = VoteFormSet(request.POST, queryset=Vote.objects.filter(game__round=round, user=user))

这将显示表单:

指定回合中游戏的下拉框,应该为赔率显示 3 个单选按钮,但我不知道将什么作为参数传递给 mymodelformset_factory .. 如果 v = Game.objects.get(pk =1)它显然只为所有游戏显示 pk=1 的游戏,我需要的是 v = Game.objects.get(pk="game who is connected to the chances about") 如果你发现我的漂移..

最佳答案

我认为您想对自定义工厂功能进行一些更改。它应该返回表单集类,而不是表单。这个怎么样:

def make_vote_formset(game_obj, extra=0):
class _VoteForm(forms.ModelForm):
score = forms.ModelChoiceField(
queryset=Odds.objects.filter(game=game_obj),
widget=forms.RadioSelect(),
empty_label=None)

class Meta:
model = Vote
exclude = ['user',]
return modelformset_factory(Vote, form=_VoteForm, extra=extra)

然后在您的 View 代码中:
current_game = Game.objects.filter(id=current_game_id)
VoteFormSet = make_vote_formset(current_game)
formset = VoteFormSet(
request.POST,
queryset=Vote.objects.filter(game__round=round, user=user))

关于Django 将自定义表单参数传递给 ModelFormset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1215040/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com