gpt4 book ai didi

python - 列表中每个项目的 Django 表单

转载 作者:太空宇宙 更新时间:2023-11-03 15:00:08 24 4
gpt4 key购买 nike

我正在尝试使用 django 制作一个网络应用程序,允许用户选择他们认为在几场比赛中获胜的人。我将比赛作为模型,其中包含主队、客队、ID 等。现在,在提交时,我希望用户将多行插入到包含用户 ID 和他们选择的团队的表中。

我尝试过使用表单集,但我无法弄清楚它们如何与不同的标签一起使用。

我目前的表格是这样的。

class PickForm(forms.ModelForm):
'''
A form that allows a user to make a pick on the
selected game
'''
error_messages = {
'no_match': ('Your selections do not match the corresponding options')
}

team_picked = forms.CharField(label=('Your choice'))

class Meta:
model = Pick
fields = ('team_picked',)

def __init__(self, *args, **kwargs):
self.user_id = kwargs.pop('user_id', None)
self.matchweek = kwargs.pop('matchweek', None)
super(PickForm, self).__init__(*args, **kwargs)

def clean_team_picked(self):
team_picked = self.cleaned_data['team_picked']
if(team_picked == self.home_team):
return team_picked
elif(team_picked == self.away_team):
return team_picked
else:
raise forms.ValidationError(
self.error_messages['no_match'],
code='no_match',
)

def save(self, commit=True):
pick = super(PickForm, self).save(commit=False)
pick.team_picked = self.cleaned_data['team_picked']
pick.user_id = self.user_id
pick.matchweek = self.matchweek
if commit:
pick.save()
return pick

谢谢!

最佳答案

不确定您对“不同标签”的意思,但看起来您想要一个模型表单集:https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#model-formsets

所以你会有类似的东西

from django.forms import modelformset_factory
from models import PickForm

PickFormSet = modelformset_factory(Pick, form=PickForm, queryset=Pick.objects.filter())

关于python - 列表中每个项目的 Django 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45179083/

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