Skip to content
This repository was archived by the owner on May 26, 2020. It is now read-only.

Commit 7e0cf41

Browse files
author
Christoph Borgolte
committed
Support Custom User models.
1 parent a974ca7 commit 7e0cf41

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

rest_framework_jwt/serializers.py

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from django.contrib.auth import authenticate
1+
from django.contrib.auth import authenticate, get_user_model
22
from rest_framework import serializers
33

44
from rest_framework_jwt.settings import api_settings
@@ -12,17 +12,24 @@ class JSONWebTokenSerializer(serializers.Serializer):
1212
"""
1313
Serializer class used to validate a username and password.
1414
15+
'username' is identified by the custom UserModel.USERNAME_FIELD.
16+
1517
Returns a JSON Web Token that can be used to authenticate later calls.
1618
"""
17-
username = serializers.CharField()
19+
20+
username_field = get_user_model().USERNAME_FIELD
1821
password = serializers.CharField(write_only=True)
1922

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()
2327

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)
2633

2734
if user:
2835
if not user.is_active:

0 commit comments

Comments
 (0)