Django TypeError,邀请用户加入'团队'

时间:2018-03-10 17:29:06

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

我想签到用户,以便能够邀请用户加入“团队”,他们可以从中选择的团队只是他们所属的团队。当我尝试输出模型UserTeams中userID =当前登录用户的所有团队的列表时,我一直得到同样的错误( init ()缺少1个必需的位置参数:'user')。

我的观点:

def invite(request):
if request.method == 'POST':
    form = InvitePlayerForm(request.POST)
    if form.is_valid():
        userteam = form.save(commit=False)
        userteam.save()

else:
    form = InvitePlayerForm()
    query = UserTeams.objects.all()
return render(request, 'teammanager/invite.html', {
    "invite": query,
    "form": form
})

我的表格:

    class InvitePlayerForm(forms.ModelForm):

    class Meta: 
        model = UserTeams
        fields = ['userID','teamID']

     def __init__(self,user,*args,**kwargs):
        super (InvitePlayerForm,self ).__init__(user,*args,**kwargs) 
        self.fields['teamID'].queryset = Team.objects.filter(id__in = 
UserTeams.objects.filter(userID = user))    

我的UserTeams模型:

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

我的HTML:

<html>

<body>

        <h4>Invite players to your team</h4>

<form method="post">

{% csrf_token %}

{{ form.as_p }}

<input class="btn btn-success" type="submit" value="Add Player"></button>


</form>

1 个答案:

答案 0 :(得分:0)

您已重新定义表单的签名,以便接受user元素。但是,在创建表单时,您实际上并没有通过该用户。你还有什么期望它进入表格?

if request.method == 'POST':
    form = InvitePlayerForm(request.user, request.POST)
    ...
else:
    form = InvitePlayerForm(request.user)

(另请注意,您的查询集会更好Team.objects.filter(userteam__UserId=user。)