Getting an error of "<Team: jaja>" needs to have a value for field "id" before this many-to-many relationship can be used

I'm trying to add team to the database but i get this error. Took a look at similar questions but none of them solved my issue. (I am new with Django)

My code looks like:

forms.py

from django.forms import ModelForm
from .models import Team


class TeamForm(ModelForm):


    class Meta:
        model = Team
        fields = ['title', 'team_country', 'team_logo']

    def __init__(self, *args, **kwargs):
        super(TeamForm, self).__init__(*args, **kwargs)

        for name, field in self.fields.items():
            field.widget.attrs.update({'class': 'input'})

models.py

from django.db import models

# Create your models here.
from django.contrib.auth.models import User
from django_countries.fields import CountryField
from .validators import validate_file_size


class Team(models.Model):
    #
    # Status

    ACTIVE = 'active'
    DELETED = 'deleted'

    CHOICES_STATUS = (
        (ACTIVE, 'Active'),
        (DELETED, 'Deleted')
    )    

    #
    # Fields

    title = models.CharField(max_length=255)
    team_country = CountryField(blank=True, null=True)    
    team_logo = models.ImageField(
        null=True, blank=True, upload_to='logos/', default="logos/logo.png",
        validators=[validate_file_size])
    members = models.ManyToManyField(User, related_name='teams')
    created_by = models.ForeignKey(User, related_name='created_teams', on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    status = models.CharField(max_length=10, choices=CHOICES_STATUS, default=ACTIVE)

    class Meta:
        ordering = ['title']
    
    def __str__(self):
        return self.title

views.py

from django.shortcuts import render
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404


from .models import Team

@login_required
def add(request):
    profile = request.user.profile
    form = TeamForm()
    if request.method == 'POST':
        form = TeamForm(request.POST, request.FILES)

        if form.is_valid():
            team = form.save(commit=False)
            team.created_by = request.user
            team.members.add(request.user)
            team.save()

            
            profile.active_team_id = team.id
            profile.save()

            return redirect('account')

    context = {'form': form}
    return render(request, 'team/add.html', context)

When I try to do it without forms like for example with only title field:

@login_required
def add(request):
    if request.method == 'POST':
        title = request.POST.get('title')

        if title:
            team = Team.objects.create(title=title, created_by=request.user)
            team.members.add(request.user)
            team.save()

            userprofile = request.user.profile
            userprofile.active_team_id = team.id
            userprofile.save()

            return redirect('account')
    
    return render(request, 'team/add.html')

It is successfully adds it. What am I doing wrong in here?

You cannot add a member to group that does not yet exist, so you need to add the user after the group has been created for example :

 if form.is_valid():
        team = form.save(commit=False)
        team.created_by = request.user
        team.members.add(request.user)
        team.save()

is now :

 if form.is_valid():
        team = form.save(commit=False)
        team.created_by = request.user
        team.save()
        team.members.add(request.user) # you can only add member after the group has been created

Same in the second snippet :

team = Team.objects.create(title=title, created_by=request.user)
        team.save()
        team.members.add(request.user)
Back to Top