我目前在一个项目中使用django-phone-field库,我也使用了graphene-django。
这是我使用 PhoneField 的自定义用户模型。
class User(AbstractBaseUser, PermissionsMixin):
"""
Custom User model to add the required phone number
"""
first_name = models.CharField(
max_length=100
)
last_name = models.CharField(
max_length=100
)
email = models.EmailField(
verbose_name='Email address',
max_length=255,
unique=True,
# Because it's unique, blank is not an option because there could be 2 with the same value ('')
blank=False,
null=True
)
phone = CustomPhoneField(
# Please note this formatting only works for US phone numbers right now
# https://github.com/VeryApt/django-phone-field#usage
# If international numbers are needed at some point, take a look at:
# https://github.com/stefanfoulis/django-phonenumber-field
E164_only=True,
unique=True
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'phone'
REQUIRED_FIELDS = ['first_name', 'last_name',]
我正在使用django-graphql-jwt来处理身份验证。
这是我的tokenAuth
查询:
mutation TokenAuth ($phone: String!, $password: String!) {
tokenAuth(phone: $phone, password: $password) {
token
payload
refreshExpiresIn
}
}
尝试执行该查询时,服务器正在检索我一个错误:
{
"errors": [
{
"message": "Object of type PhoneNumber is not JSON serializable",
"locations": [
{
"line": 2,
"column": 5
}
],
"path": [
"tokenAuth"
]
}
],
"data": {
"tokenAuth": null
}
}
to_python
我通过覆盖PhoneField的方法临时做了一个猴子补丁,像这样:
class CustomPhoneField(PhoneField):
"""
I had to override this to_python method because the phone field is now being used as the username field.
In GraphQL JWT I was getting the following exception:
Object of type PhoneNumber is not JSON serializable
I don't really understand the implications of overriding this method.
"""
def to_python(self, value):
# Called during deserialization and from clean() methods in forms
if not value:
return None
elif isinstance(value, PhoneNumber):
return str(value)
return str(value)
我想知道这个问题的正确解决方案是什么,并且还想了解它是如何工作的,这样我就可以用更优雅的解决方案继续前进。