2017-07-19 32 views
1

我正在嘗試使用django製作一個web應用程序,該程序允許用戶選擇他們相信誰會在幾場比賽中獲勝的人。我將比賽作爲一個模型,包括主隊,客隊,身份證等。現在提交時,我希望用戶將多行插入到具有用戶標識和所選團隊的表中。Django表單列表中的每個項目

我已經嘗試使用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 

謝謝!

回答

相關問題