DRF SimpleJWT remove password and add date field

北慕城南 提交于 2021-02-17 07:10:39

问题


I created a custom user model extending from AbstractBaseUser where the only data I'm getting from the user is a userID, user (the username field) and date (required and in the format dd-mm-yyyy) and the creation of the user works fine as you can see from the DB in the next image

Used password = None and last_login = None to refer i didn't want password and last_login tables.

Then, created a view where only authenticated users can access.

To handle the authentication, used simpleJWT. In urls.py

# JWT Token
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain'),
# Get a new token before the old expires.
path('api/token/refresh/', TokenRefreshView.as_view, name='token_refresh'),

And by going to http://127.0.0.1:8000/api/token/ , this is what I see (which works as expected)

I've tested previously with User and Password in a different project with user model that included that data (User and Password) and worked fine. Now, here, if I try Posting with an existing user but with no password, I get a warning and not being able to Post

This field may not be blank.

If i add anything other than a blank space, the following error appears

TypeError at /api/token/ object of type 'NoneType' has no len()

How can I remove the Password field? Also, how could I add a Date field too?


回答1:


I also faced the same problem and somehow I have manage to solve this problem.

Here is the solution,

  1. Override the TokenObtainPairSerializer class __init__ method like below,

  2. Use del password so It wont ask you the password and add whatever fields you want.

class CustomSerializer(TokenObtainPairSerializer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields[self.username_field] = serializers.CharField() del self.fields['password'] self.fields['last_login'] = serializers.DateField(initial=datetime.date.today)

This works really well.

Here is the reference - How to skip or remove password field in simplejwt token authentication in django rest framework??

Let me know if anyone have better solution of this.



来源:https://stackoverflow.com/questions/62066402/drf-simplejwt-remove-password-and-add-date-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!