OAuth2 自定义基本用户模型

OAuth2 custom basic user model

我正在使用rest_framework_social_oauth2

我想对 oauth.User 进行最小的更改。搜索通过AbstractUser交换AbstractBaseUser并添加PermissionMixin。但是没有任何效果。

我的应用程序> 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()

我的settings.py:

AUTH_USER_MODEL ='userTest.MyUser'

如教程所示,没有进行 makemigrations 和 migrate。

错误:

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'

我们成功了。我将在这里为那些想要改进 OAuth2.user 的人提供一个完整的示例。在我们的例子中,我们自动创建了用户名。

PS: 需要创建 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