如何在 django-graphql-auth 中使用自定义注册突变
Posted
技术标签:
【中文标题】如何在 django-graphql-auth 中使用自定义注册突变【英文标题】:how to use custom register mutation with django-graphql-auth 【发布时间】:2020-10-28 21:04:57 【问题描述】:django-graphql-auth 是一个很棒的包,但文档并没有说明模型与自定义用户模型的关联。
我正在寻找一种方法来使用此软件包,并为申请人和雇主两种用户类型提供自定义注册突变
class User(AbstractUser):
email = models.EmailField(blank=False,
max_length=255,
verbose_name="email address")
is_applicant = models.BooleanField(default=False)
is_employer = models.BooleanField(default=False)
USERNAME_FIELD = "username"
EMAIL_FIELD = "email"
class Applicant(models.Model):
user = models.OneToOneField(
User,
on_delete=models.CASCADE,
primary_key=True,
)
fullname = models.CharField(max_length=255, null=True)
class Employer(models.Model):
user = models.OneToOneField(
User,
on_delete=models.CASCADE,
primary_key=True,
)
company_name = models.CharField(max_length=225, null=True)
要实现的变异目标:
mutation
registerApplicant(
input:
email: "new_applicant@email.com",
username: "new_applicant",
password1: "createsuperpassword",
password2: "createsuperpassword",
isApplicant: true,
applicant
fullname: "New Applicant"
)
success,
errors,
token,
refreshToken
mutation
registerEmployer(
input:
email: "new_employer@email.com",
username: "new_employer",
password1: "createsuperpassword",
password2: "createsuperpassword",
isEmployer: true,
employer
fullname: "New Employer"
)
success,
errors,
token,
refreshToken
【问题讨论】:
【参考方案1】:您可以仅使用 graphql_jwt 完成整个过程,首先您需要定义输入;像这样:
class ApplicantInfoInput(graphene.InputObjectType):
email = graphene.String(required=True)
username = graphene.String(required=True)
password1 = graphene.String(required=True)
password2 = graphene.String(required=True)
is_applicant = graphene.Boolean(required=True)
fullname = graphene.String(required=True)
那么突变类应该是这样的:
from graphql_jwt.shortcuts import get_token, create_refresh_token
from ..models import User, Applicant
class UserCreateMutation(graphene.Mutation):
user = graphene.Field(UserType)
success = graphene.Boolean()
token = graphene.String()
refresh_token = graphene.String()
class Arguments:
input = ApplicantInfoInput(required=True)
@staticmethod
def mutate(root, info, input=None):
try:
user = User.objects.get(username=input.username)
except User.DoesNotExist as e:
user = None
if user:
raise Exception('User Already Exists!')
else:
user_instance = Applicant(fullname=input.fullname)
user_instance.user.email = input.email
user_instance.user.set_password(input.password1)
user_instance.user.is_applicant = True
user_instance.save()
token = get_token(user_instance)
refresh_token = create_refresh_token(user_instance)
return UserCreateMutation(user=user_instance,
token=token,
refresh_token=refresh_token,
success=True)
【讨论】:
以上是关于如何在 django-graphql-auth 中使用自定义注册突变的主要内容,如果未能解决你的问题,请参考以下文章
pip - 如何使用预先构建的***而不是再次拉动 git 以避免冲突?