DEV Community

Dimitrios Desyllas
Dimitrios Desyllas

Posted on

Why I am unable to set Groups despite user having an Id?

I am hacking into Django and I am stuck on this issue:

I made a custom user model:

from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
    bio = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.first_name+' '+self.last_name

And I try to save it like this:

from app_auth.models import User
from django.contrib.auth.models import Group

from django.db import transaction
…

I made a custom user model and I try to save it using a service that can be fetched from a service locator pattern. To keep it simple the service is:

# Source - https://stackoverflow.com/q/80008079
# Posted by Dimitrios Desyllas
# Retrieved 2026-10-05, License - CC BY-SA 4.0

from app_auth.models import User
from django.contrib.auth.models import Group

from django.db import transaction

class UserService:

    @transaction.atomic
    def create(self,
               username: str,
               email: str,
               first_name: str,
               last_name: str,
               groups: list[Group],
               bio: str | None = None) -> User:

        user = User.objects.create_user(
            username=username,
            first_name=first_name,
            last_name=last_name,
            email=email,
            bio=bio, #TODO: XSS Sanitize
        )

        print("USER ID: "+str(user.id))

        for group in groups:
            print("GROUP ID: "+str(group.pk))

        user.groups.set(groups)

        user.save()
        return user

Enter fullscreen mode Exit fullscreen mode

(Print statements are used for debugging)

And my model is:

# Source - https://stackoverflow.com/q/80008079
# Posted by Dimitrios Desyllas
# Retrieved 2026-10-05, License - CC BY-SA 4.0

from django.db import models
from django.contrib.auth.models import AbstractUser

# Create your models here.
class User(AbstractUser):
    bio = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.first_name+' '+self.last_name

Enter fullscreen mode Exit fullscreen mode

But despite both user and Groups have Ids (according to print statement):

USER ID: 4
GROUP ID: 4
Enter fullscreen mode Exit fullscreen mode

I am getting this error:

"<User: XXXX XXXXX>" needs to have a value for field "id" before this many-to-many relationship can be used.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)