Django表单列表中的每个项目

时间:2017-07-19 00:23:30

标签: python django forms

我正在尝试使用django创建一个webapp,允许用户选择他们认为胜利者将参加几场比赛的人。我将游戏作为一个拥有主队,客场球队,身份证等的模特。现在提交时,我希望用户在具有用户ID和他们选择的团队的表中插入多行。

我尝试过使用formset,但我无法弄清楚它们如何使用不同的标签。

我目前的表格就是这个。

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

谢谢!

1 个答案:

答案 0 :(得分:1)

不确定您对“不同标签”的意思,但看起来您需要一个模型表单集: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())