1
- from django .contrib .auth import authenticate
1
+ from django .contrib .auth import authenticate , get_user_model
2
2
from rest_framework import serializers
3
3
4
4
from rest_framework_jwt .settings import api_settings
@@ -12,17 +12,24 @@ class JSONWebTokenSerializer(serializers.Serializer):
12
12
"""
13
13
Serializer class used to validate a username and password.
14
14
15
+ 'username' is identified by the custom UserModel.USERNAME_FIELD.
16
+
15
17
Returns a JSON Web Token that can be used to authenticate later calls.
16
18
"""
17
- username = serializers .CharField ()
19
+
20
+ username_field = get_user_model ().USERNAME_FIELD
18
21
password = serializers .CharField (write_only = True )
19
22
20
- def validate (self , attrs ):
21
- username = attrs .get ('username' )
22
- password = attrs .get ('password' )
23
+ def __init__ (self , * args , ** kwargs ):
24
+ """Dynamically add the USERNAME_FIELD to self.fields."""
25
+ super (JSONWebTokenSerializer , self ).__init__ (* args , ** kwargs )
26
+ self .fields [self .username_field ] = serializers .CharField ()
23
27
24
- if username and password :
25
- user = authenticate (username = username , password = password )
28
+ def validate (self , attrs ):
29
+ credentials = {self .username_field : attrs .get (self .username_field ),
30
+ 'password' : attrs .get ('password' )}
31
+ if all (credentials .values ()):
32
+ user = authenticate (** credentials )
26
33
27
34
if user :
28
35
if not user .is_active :
0 commit comments