Modify ObtainAuthToken to use the User model's USERNAME_FIELD and password for authentication instead of assuming username and password. #9674
+42
−20
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
Django’s default user model uses
usernameandpasswordfor authentication. However, when a custom user model is defined withUSERNAME_FIELD = 'email', Django correctly uses email and password for authentication.The issue was that Django REST Framework's
obtain_auth_tokenendpoint (used for TokenAuthentication) still expectedusernameandpassword, even when a custom user model usedemailinstead ofusername.Fix
This update modifies the
ObtainAuthTokenview to dynamically useUSERNAME_FIELDinstead of assumingusername. Now, authentication works consistently, whether using the built-in User model or a custom one, with no inconsistencies.Changes Made:
ObtainAuthTokennow retrieves theUSERNAME_FIELDfrom the user model.USERNAME_FIELDandpassword, ensuring compatibility with both built-in and custom user models.Impact
USERNAME_FIELD = 'email') can now log in usingemailandpasswordinstead ofusernameandpassword.default Usermodel or acustom Usermodel whereUSERNAME_FIELD = 'username'can continue logging in usingusernameandpasswordas expected.