我希望登录用户能够将用户添加到他们创建的团队中。目前我创建了一个表单,允许用户选择他们想要添加的用户和团队,但他们可以从数据库中的每个团队中选择,而不仅仅是他们创建的团队。有任何想法吗?这些是我的模型,视图和我创建的形式。还应该感谢有关放入HTML文件的内容的帮助。
型号:
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):
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']
HTML:
{% extends "teammanager/header.html" %}
{% block content %}
<html>
<body>
<h4>Invite players to your team</h4>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
</form>
{% endblock %}
答案 0 :(得分:0)
像这样修改你的表单它会根据userteam对象进行FK过滤。
class InvitePlayerForm(forms.ModelForm):
class Meta:
model = UserTeams
fields = ['userID','teamID']
def __init__(self,user,*args,**kwargs):
super(InvitePlayerForm,self ).__init__(*args,**kwargs)
self.fields['teamID'].queryset = Team.objects.filter(id__in = UserTeam.objects.filter(userID = user))