Hi, I'm having an issue trying to create a mutation for updating a custom user model. According to the docs (https://docs.graphene-python.org/projects/django/en/latest/mutations/):
"Form mutations will call is_valid() on your forms. If the form is valid then the class method perform_mutate(form, info) is called on the mutation. Override this method to change how the form is saved or to return a different Graphene object type. If the form is not valid then a list of errors will be returned. These errors have two fields: field, a string containing the name of the invalid form field, and messages, a list of strings with the validation messages."
For me, perform_mutate is being called correctly when the form is valid (as expected), but my issue is that form errors are not being returned when the form is invalid. The endpoint simply returns a null user.
Code:
class UserType(DjangoObjectType):
class Meta:
model = User
exclude_fields = ('password',)
class UpdateUser(DjangoModelFormMutation):
user = graphene.Field(UserType)
class Meta:
form_class = UpdateUserForm
@login_required
def perform_mutate(form, info):
print("This only runs when the form is valid")
return UpdateUser(user=info.context.user)
class Mutation(graphene.ObjectType):
update_user = UpdateUser.Field()
Model:
class User(AbstractUser):
SEX_CHOICES = (
('M', 'Male'),
('F', 'Female'),
('O', 'Other')
)
is_tutor = models.BooleanField(default=False)
is_student = models.BooleanField(default=False)
sex = models.CharField(max_length=1, choices=SEX_CHOICES, verbose_name="Sex", null=True, blank=True)
dob = models.DateField(verbose_name="Date of Birth", null=True, blank=True)
academic_year = models.CharField(max_length=2, choices=CLASS_CHOICES, verbose_name="Academic Year", null=True, blank=True)
major = models.CharField(max_length=50, choices=MAJOR_CHOICES, verbose_name="Major", null=True, blank=True)
Form:
class UpdateUserForm(ModelForm):
class Meta:
model = User
fields = ('is_tutor', 'is_student', 'sex', 'dob', 'academic_year', 'major')
Query:
mutation {
updateUser(input: {
major: "INVALID_MAJOR"
sex: "INVALID_SEX"
dob: "1998-05-25"
}) {
user {
username
}
}
}
I am expecting to receive error messages based on the given query, but instead I am only receiving:
{
"data": {
"updateUser": {
"user": null
}
}
}
When the form is valid however, the perform_mutate method is being called as expected.
Have I done something wrong? Thanks.
I am thinking you need to explicitly ask for errors as part of the mutation, like so:
mutation {
updateUser(input: {
major: "INVALID_MAJOR"
sex: "INVALID_SEX"
dob: "1998-05-25"
}) {
user {
username
},
errors {
field, messages
}
}
}
Ah yes, that totally makes sense now, and now the errors are being raised as expected. Thanks for that clarification!
Most helpful comment
I am thinking you need to explicitly ask for errors as part of the mutation, like so: