Django ValueError - 将用户添加到userteam

时间:2018-03-31 12:11:48

标签: python django django-models django-forms django-views

我正在创建一个Django表单,您可以将用户添加到UserTeam(下面的UserTeams模型)。 “邀请”页面(下方)查询团队模型以获取当前团队的ID,然后将其分配给“teamID”,因此您只能将用户添加到当前团队。 (我已禁用此字段,因此用户无法更改团队)然后,用户选择要添加的用户,然后提交表单。我正在尝试使用Team“Kate FC”,并添加玩家'steven'。但是,当我提交表单时,我收到此错误:

/ teams / 1 / invite /

的ValueError

无法指定“'Kate FC'”:“UserTeams.teamID”必须是“团队”实例。

这个错误意味着什么?

class UserTeams(models.Model):
    userID = models.ForeignKey(User,on_delete=models.CASCADE)
    teamID = models.ForeignKey(Team,on_delete=models.CASCADE)

class Team(models.Model):
    name = models.CharField(max_length=100)
    venue = models.CharField(max_length=100)
    countryID = models.ForeignKey(Countries, on_delete=models.CASCADE)
    owner = models.ForeignKey(User)


def invite(request, teamID):
    try:
        query = Team.objects.get(id=teamID)
    except:
        raise Http404()
    if request.method == 'POST':
        form = InvitePlayerForm(request.POST or None, initial={'teamID': query})
        if form.is_valid():
            userteam = form.save(commit=False)
            userteam.save()
        return redirect('teammanager/teams.html')
    else:

        form = InvitePlayerForm(initial={'teamID': query})
        query = Team.objects.get(id=teamID)
    return render(request, 'teammanager/invite.html', {
        "team": query,                  
        "form": form
   })

形式:

    class InvitePlayerForm(forms.ModelForm):
    teamID = forms.CharField(disabled=True)
    class Meta:

        model = UserTeams
        fields = ['teamID','userID']

1 个答案:

答案 0 :(得分:1)

teamID是外键,因此您应该使用模型选择字段而不是CharField:

class InvitePlayerForm(forms.ModelForm):
    teamID = forms.ModelChoiceField(queryset=Team.objects.all(), disabled=True)
    ...

或者您可以在__init__方法中禁用该字段。

class InvitePlayerForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(InvitePlayerForm, self).__init__(*args, **kwargs)
        self.fields['teamID'].disabled = True
    ...

或者,您可以将teamID字段保留在表单之外,并在保存表单时设置值:

if form.is_valid():
    userteam = form.save(commit=False)
    userteam.teamID = query
    userteam.save()