Volt
Volt

Reputation: 27

How to add request.user to manytomanyfield for team members in django?

I was trying to create a custom team model having a manytomanyfield for team members, now i have a form that allows users to create their own team(s), but i dont understand how i can add request.user to the members of the team. Below are the codes:

models.py

class Team(models.Model):
    name = models.CharField(max_length=64, unique=True)
    description = models.CharField(max_length=1024)
    created_at = models.DateTimeField(auto_now_add=True)
    members = models.ManyToManyField(User, through='Member')

    def __str__(self):
        return f"Team: {self.name} created on {self.created_at}\nMember(s): {self.members}"


class Member(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    team = models.ForeignKey(Team, on_delete=models.CASCADE, blank=True)

forms.py

class TeamRegistrationForm(ModelForm):
    class Meta:
        model = Team
        fields = ["name", "description"]

views.py

@login_required(login_url="/login/")
def teamregister(request):
    if request.method == "POST":
        form = TeamRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            form.instance.members.add(request.user) # doesn't work :[
            print(form.save())
            messages.success(request, "Your team has been successfully registered!")
            return redirect("dashboard")
    else:
        form = TeamRegistrationForm()

    return render(request, "users/team.html", {"form": form})

I tried to use form.instance.members.add(request.user) to add the logged in user to the member of the team but it didn't work. Please help :[

Upvotes: 1

Views: 115

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477230

It is added to the relation, but you do not print the items in the relation. You print the manager. Indeed, you write {self.members}, and that is the manager, you should rewrite this to {self.manager.all()}. A Manager will, unless you implement it otherwise return ModelName.None:

class Team(models.Model):
    # …

    def __str__(self):
        return f'Team: {self.name} created on {self.created_at}\nMember(s): {self.members.all()}'

Upvotes: 1

Related Questions