问题描述
我创建了一个自AbstractBaseUser扩展的自定义用户模型,其中我从用户那里获得的唯一数据是userID,用户(用户名字段)和日期(必需,格式为 dd-mm-yyyy ),并且您可以很好地创建用户,就像您在下一张图片中从数据库中看到的一样
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
使用password = None
和last_login = None
来表示我不需要密码和last_login表.
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.
要处理身份验证,请使用 simpleJWT .在urls.py
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'),
然后转到 http://127.0.0.1:8000/api/token/,这就是我所看到的(按预期方式工作)
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
如果我添加空格以外的任何内容,则会出现以下错误
If i add anything other than a blank space, the following error appears
如何删除密码字段?另外,我也该如何添加日期字段?
How can I remove the Password field? Also, how could I add a Date field too?
推荐答案
我也遇到了同样的问题,并且以某种方式设法解决了这个问题.
I also faced the same problem and somehow I have manage to solve this problem.
这是解决方案,
-
覆盖如下所示的
TokenObtainPairSerializer
类__init__
方法
使用del password
,因此它不会询问您密码并添加您想要的任何字段.
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)
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)
这真的很好.
这里是参考-?
让我知道是否有人对此有更好的解决方案.
Let me know if anyone have better solution of this.
这篇关于DRF SimpleJWT删除密码并添加日期字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!