我使用Django REST Framework创建了一个自定义用户,该用户使用电话号码而不是用户名进行身份验证。我可以使用create_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')
managers.py
:
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)
urls.py
:
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'))
]
settings.py
:
AUTH_USER_MODEL = 'customauth.User'
我想念什么或做错什么了?
注意:不是this question的副本,{{3}}是使用UserProfile
类而不是子类AbstractBaseUser
处理的。
答案 0 :(得分:1)
一种方法是像这样覆盖身份验证后端:
convert = WorksheetFunction.SumIfs(Sheets("Convert").Range("C:C"), _
Sheets("Convert").Range("A:A"), Sheets("Vista").Range("L8"), _
Sheets("Convert").Range("D:D"), Sheets("Vista").Range("C2"), _
Sheets("Convert").Range("E:E"), Sheets("Vista").Range("AC4"))
Sheets("series").Range("L2").FormulaR1C1 = _
"=RC[-8]*"&convert&"
并使用以下命令更新您的settings.py:
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