title: Adding a user to a group using django rest framework programmatically
body: <p>I want to be able to attach a user to a group upon creation.</p>
  <p>Here is the result of select * from auth_group:</p>
  <p><img src="https://i.stack.imgur.com/WI5Ft.png" alt="image screenshoot" /></p>
  <p>Here is the my serializer.py file:</p>
  <pre><code>from rest_framework import serializers
  
  from .models import User
  
  
  class UserSerializer(serializers.ModelSerializer):
  
  class Meta(object):
      model = User
      fields = ('id', 'email', 'first_name', 'last_name', 'phone', 'address', 'is_active', 'is_staff',
                'is_superuser', 'date_joined', 'password',)
      extra_kwargs = {'password': {'write_only': True}}
  </code></pre>
  <p>Here is my model.py file:</p>
  <pre><code>from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  from django.contrib.auth.models import PermissionsMixin, UserManager, Group
  from django.db import models, transaction
  
  # Create your models here.
  from django.utils import timezone
  
  
  class UserManager(BaseUserManager):
  
      def _create_user(self, email, password, **extra_fields):
      &quot;&quot;&quot;
      Creates and saves a User with the given email,and password.
      &quot;&quot;&quot;
      if not email:
          raise ValueError('User must have an email address')
      email = self.normalize_email(email)
      if not extra_fields[&quot;group_id&quot;]:
          raise ValueError('User must have group id')
      try:
          with transaction.atomic():
              user = self.model(email=email, **extra_fields)
              group = Group.objects.get(extra_fields[&quot;group_id&quot;])
              group.user_set.add(user)
              user.set_password(password)
              user.save(using=self._db)
              return user
      except:
          raise
  
  def create_user(self, email, password=None, **extra_fields):
      extra_fields.setdefault('is_staff', False)
      extra_fields.setdefault('is_superuser', False)
      return self._create_user(email, password, **extra_fields)
  
  def create_superuser(self, email, password, **extra_fields):
      extra_fields.setdefault('is_staff', True)
      extra_fields.setdefault('is_superuser', True)
  
      return self._create_user(email, password=password, **extra_fields)
  
  
  class User(AbstractBaseUser, PermissionsMixin):
  &quot;&quot;&quot;
  An abstract base class implementing a fully featured User model with
  admin-compliant permissions.
  
  &quot;&quot;&quot;
  email = models.EmailField(max_length=40, unique=True)
  first_name = models.CharField(max_length=30, blank=True)
  last_name = models.CharField(max_length=30, blank=True)
  phone = models.CharField(max_length=20, blank=True)
  address = models.CharField(max_length=30, blank=True)
  is_active = models.BooleanField(default=True)
  is_staff = models.BooleanField(default=False)
  date_joined = models.DateTimeField(default=timezone.now)
  
  objects = UserManager()
  
  USERNAME_FIELD = 'email'
  REQUIRED_FIELDS = ['first_name', 'last_name', 'phone']
  
  def get_full_name(self):
      &quot;&quot;&quot;&quot; Used to display user's full name &quot;&quot;&quot;
      return &quot;{}, {}&quot;.format(self.first_name, self.last_name)
  
  def __srt__(self):
      return self.email
  
  def save(self, *args, **kwargs):
      super(User, self).save(*args, **kwargs)
      return self
  </code></pre>
  <p>And finally, here is my view.py:</p>
  <pre><code>class CreateUserAPIView(APIView):
  # Allow any user (authenticated or not) to access this url
  permission_classes = (AllowAny,)
  
  def post(self, request):
      user = request.data
      serializer = UserSerializer(data=user)
      serializer.is_valid(raise_exception=True)
      serializer.save()
      return Response({&quot;user&quot;: serializer.data, &quot;status&quot;: status.HTTP_200_OK})
  </code></pre>
  <p>I want for this request:</p>
  <pre><code>{
  &quot;email&quot;: &quot;myemail@gmail.com&quot;,
  &quot;first_name&quot;: &quot;myfirst_name&quot;,
  &quot;last_name&quot;: &quot;mylast_name&quot;,
  &quot;phone&quot;: &quot;000556660&quot;,
  &quot;address&quot;: &quot;myaddress&quot;,
  &quot;password&quot;: &quot;mypassword&quot;,
  &quot;group_id&quot;: 5
  }
  </code></pre>
  <p>To get this response:</p>
  <pre><code>{
  &quot;status&quot;: 200,
  user: {
  &quot;email&quot;: &quot;myemail@gmail.com&quot;,
  &quot;first_name&quot;: &quot;myfirst_name&quot;,
  &quot;last_name&quot;: &quot;mylast_name&quot;,
  &quot;phone&quot;: &quot;000556660&quot;,
  &quot;address&quot;: &quot;myaddress&quot;,
  &quot;password&quot;: &quot;mypassword&quot;,
  &quot;groups&quot;: [5]
  }
  }
  </code></pre>
  <p>I have followed this link <a href="https://stackoverflow.com/questions/6288661/adding-a-user-to-a-group-in-django">Adding a user to a group in django</a> but it's not helping me.</p>
  <p>Thanks, any help would be appreciated.</p>