【发布时间】:2016-06-27 20:25:23
【问题描述】:
我已遵循Django REST framework JWT 中指定的所有说明。但是当我使用我的自定义用户模型登录时,它不起作用。
settings.py
...
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
}
自定义用户管理器:
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **kwargs):
if not email:
raise ValueError('Users must have a valid email address.')
user = self.model(
email=self.normalize_email(email), full_name=kwargs.get('full_name')
)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **kwargs):
user = self.create_user(email, password, **kwargs)
user.is_admin = True
user.save()
return user
这是我用于登录的views.py:
class LoginView(views.APIView):
def post(self, request, format=None):
data = json.loads(request.body)
email = data.get('email', None)
password = data.get('password', None)
account = authenticate(email=email, password=password)
if account is not None:
if account.is_active:
login(request, account)
serialized = UserSerializer(account)
return Response(serialized.data)
else:
return Response({
'status': 'Unauthorized',
'message': 'This account has been disabled.'
}, status=status.HTTP_401_UNAUTHORIZED)
else:
return Response({
'status': 'Unauthorized',
'message': 'Username/password combination invalid.'
}, status=status.HTTP_401_UNAUTHORIZED)
【问题讨论】:
-
向您显示的错误是什么?有什么不好的地方?
-
没有错误。一切都像未配置一样工作。
-
你检查你安装的应用了吗?
-
是的,它也适用于默认登录 DRF 登录 API (api-token-auth)。
-
默认情况下,令牌应在向
POST /api-token-auth/的请求中返回。您如何尝试获取令牌?
标签: django django-rest-framework