Search code examples
djangopython-3.xdjango-rest-frameworkdjango-socialauth

OAuth2 custom basic user model


I am using rest_framework_social_oauth2

I want to make a minimum change in oauth.User. Search to exchange AbstractBaseUser by AbstractUser and add PermissionMixin. But nothing works.

My app> models.py:

 from django.db import models
 from django.contrib.auth.models import AbstractUser, PermissionsMixin, UserManager

 class MyUser(AbstractUser, PermissionsMixin):
      country_code = models.CharField(max_length=10, blank=True)
      objects = UserManager()

My settings.py:

AUTH_USER_MODEL ='userTest.MyUser'

As indicated by tutorials, not did makemigrations and migrate.

ERRO:

File "/Users/luisdemarchi/Git/django/.env/lib/python3.5/site-packages/django/db/models/manager.py", line 277, in get self.model._meta.swapped,

AttributeError: Manager isn't available; 'auth.User' has been swapped for 'userTest.MyUser'


Solution

  • We managed. I'll put here a complete example for those who want to make an improvement in OAuth2.user. In our case we created the username automatically.

    PS: Need create class AuthManager()

    userTest(myApp) > models.py

    import uuid as uuid
    from django.contrib.auth.models import BaseUserManager, AbstractUser
    from django.db import models
    
    from rest_framework import exceptions
    
    class AuthManager(BaseUserManager):
        def create_user(self, email, username=None, password=None):
            if not email:
                raise exceptions.AuthenticationFailed('Users must have an username')
    
            username = email.split("@")[0]
    
            user = self.model(username=username)
            user.set_password(password)
            user.save(using=self._db)
            return user
    
        def create_superuser(self, email, password, username=None):
            user = self.create_user(email=email, password=password)
            user.is_admin = True
            user.save(using=self._db)
            return user
    
    class User(AbstractUser):
        uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
        is_test = models.BooleanField(default=True)
        is_admin = models.BooleanField(default=False)
    
        objects = AuthManager()
    

    userTest(myApp) > views.py

    from rest_framework import viewsets
    
    from apps.userTest.models import User
    from apps.userTest.serializers import UserSerializer
    
    class UserViewSet(viewsets.ReadOnlyModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserSerializer