(Django)无法更新/添加到manytomany字段

时间:2018-05-21 20:10:19

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

所以我目前正处于一个项目中,我希望团队领导者更新他们的团队并添加/删除成员但是它不起作用并且为什么我尝试通过添加/删除方式来实现它,就像你在代码中看到的那样下。

我该如何解决这个问题?

模型

class TeamMembership(models.Model):
    user = models.ForeignKey(User)
    team = models.ForeignKey(Team)
    ingroup = models.BooleanField(default=False)
    leader = models.BooleanField(default=False)
    groupleader = models.BooleanField(default=False)

class TeamGroup(models.Model):
    name = models.CharField(max_length=50)
    team = models.ForeignKey(Team)
    ingroup = models.ManyToManyField(TeamMembership, blank=True)

目前代码是

@login_required
def teamsettings_members_updategroup(request, team_pk, group_pk):
    requested_team = get_object_or_404(Team, pk=team_pk)
    for member in requested_team.teammembership_set.all().order_by('-leader'):
        if member.user.pk == request.user.pk and member.leader:
            group = TeamGroup.objects.get(pk=group_pk)
            if request.method == 'POST':
                name  = request.POST['name']
                users = request.POST.getlist('users[]')
                group.name = name
                for user in users:
                    for ingroup in group.ingroup.all():
                        if ingroup.pk != user:
                            group.ingroup.remove(user)
                            TeamMembership.objects.filter(pk=user).update(ingroup=False)
                    group.ingroup.add(user)
                    TeamMembership.objects.filter(pk=user).update(ingroup=True)
                group.save()
                return redirect('teamsettings_members', team_pk)
            feedback = FeedbackSupportForm()
            context = {
                'feedback'      : feedback,
                'group'         : group,
                'requested_team': requested_team,
            }
            return render(request, 'team/update_group.html', context)
    return redirect('team', team_pk)

0 个答案:

没有答案