Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Can';t使用Django REST Framework自定义用户扩展AbstractBaseUser登录_Python_Django_Django Rest Framework_Django Rest Auth - Fatal编程技术网

Python Can';t使用Django REST Framework自定义用户扩展AbstractBaseUser登录

Python Can';t使用Django REST Framework自定义用户扩展AbstractBaseUser登录,python,django,django-rest-framework,django-rest-auth,Python,Django,Django Rest Framework,Django Rest Auth,使用Django REST框架,我创建了一个自定义用户,该用户使用电话号码而不是用户名进行身份验证。我可以使用create\u superuser成功创建超级用户,并且超级用户确实出现在数据库中。但是,当我进入登录页面时,我无法使用我选择的电话号码和密码登录(是的,我已对密码/电话号码进行了两次和三次检查,并尝试了多个不同的密码/电话号码)。这是我的自定义用户类“models.py”文件的(存根): class User(AbstractBaseUser, PermissionsMixin):

使用Django REST框架,我创建了一个自定义用户,该用户使用电话号码而不是用户名进行身份验证。我可以使用
create\u superuser
成功创建超级用户,并且超级用户确实出现在数据库中。但是,当我进入登录页面时,我无法使用我选择的电话号码和密码登录(是的,我已对密码/电话号码进行了两次和三次检查,并尝试了多个不同的密码/电话号码)。这是我的自定义用户类“
models.py”文件的(存根):

class User(AbstractBaseUser, PermissionsMixin):
    phone_regex = RegexValidator(
    regex=r'^\+?1?\d{9,15}$',
    message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")

    phone_number = models.CharField(_('phone number'), unique=True, validators=[phone_regex], max_length=17, blank=True)
    .
    .
    .
    objects = UserManager()
    USERNAME_FIELD = 'phone_number'
    REQUIRED_FIELDS = ['first_name', 'last_name']
serializers.py

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'phone_number', 'groups')
class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, phone_number, password, **extra_fields):
        """
        Creates and saves a User with the given phone number and password.
        """
        if not phone_number:
            raise ValueError('The phone number must be set')
        user = self.model(phone_number=phone_number, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, phone_number, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(phone_number, password, **extra_fields)

    def create_superuser(self, phone_number, password, **extra_fields):
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(phone_number, password, **extra_fields)
from django.conf.urls import url, include
from rest_framework import routers
from customauth import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
AUTH_USER_MODEL = 'customauth.User'
managers.py

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'phone_number', 'groups')
class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, phone_number, password, **extra_fields):
        """
        Creates and saves a User with the given phone number and password.
        """
        if not phone_number:
            raise ValueError('The phone number must be set')
        user = self.model(phone_number=phone_number, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, phone_number, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(phone_number, password, **extra_fields)

    def create_superuser(self, phone_number, password, **extra_fields):
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(phone_number, password, **extra_fields)
from django.conf.urls import url, include
from rest_framework import routers
from customauth import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
AUTH_USER_MODEL = 'customauth.User'
url.py

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'phone_number', 'groups')
class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, phone_number, password, **extra_fields):
        """
        Creates and saves a User with the given phone number and password.
        """
        if not phone_number:
            raise ValueError('The phone number must be set')
        user = self.model(phone_number=phone_number, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, phone_number, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(phone_number, password, **extra_fields)

    def create_superuser(self, phone_number, password, **extra_fields):
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(phone_number, password, **extra_fields)
from django.conf.urls import url, include
from rest_framework import routers
from customauth import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
AUTH_USER_MODEL = 'customauth.User'
settings.py

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'phone_number', 'groups')
class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, phone_number, password, **extra_fields):
        """
        Creates and saves a User with the given phone number and password.
        """
        if not phone_number:
            raise ValueError('The phone number must be set')
        user = self.model(phone_number=phone_number, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, phone_number, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(phone_number, password, **extra_fields)

    def create_superuser(self, phone_number, password, **extra_fields):
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(phone_number, password, **extra_fields)
from django.conf.urls import url, include
from rest_framework import routers
from customauth import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
AUTH_USER_MODEL = 'customauth.User'
我错过了什么或做错了什么


注意:不是的副本,它处理使用
UserProfile
类,而不是子类化
AbstractBaseUser

一种方法是像这样覆盖身份验证后端:

class CustomAuthBackend(object):
    def authenticate(self, request):
        phone = request.POST.get('username') 
        password = request.POST.get('password')

        if not phone:
            return None
        try:
            user = CustomUser.objects.get(phone=phone)
            if user.check_password(password):
                return user
        except CustomUser.DoesNotExist:
            # exception handling
            return None
        return None
并使用以下内容更新settings.py:

AUTHENTICATION_BACKENDS = ['path.to.your.CustomAuthBackend']

你设计好这个计划了吗?@ruddra我该怎么设计呢?我是否应该使用链接中指示的
默认\u身份验证\u类
documentation@ruddra不起作用这给了我一个
authenticate()缺少1个必需的位置参数:“password”
错误,因为在django rest框架代码中,它在没有密码字段的情况下调用
authenticate
仍然是空的:(@ruddra如果它有帮助,无论我在网站上创建帐户时出于什么原因(例如,不是通过控制台),它都不会要求密码对不起,我的错。我在回答中犯了一个错误,
get_user()接受1个位置参数,但给出了2个