Skip to content

Commit baa7c13

Browse files
committed
Fix DjangoModelFormMutation
1 parent 0da06d4 commit baa7c13

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

graphene_django/forms/mutation.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,17 @@ def __init_subclass_with_meta__(
162162
_meta=_meta, input_fields=input_fields, **options
163163
)
164164

165+
@classmethod
166+
def mutate_and_get_payload(cls, root, info, **input):
167+
form = cls.get_form(root, info, **input)
168+
169+
if form.is_valid():
170+
return cls.perform_mutate(form, info)
171+
else:
172+
errors = ErrorType.from_errors(form.errors)
173+
174+
return cls(errors=errors)
175+
165176
@classmethod
166177
def perform_mutate(cls, form, info):
167178
obj = form.save()

graphene_django/forms/tests/test_mutation.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,12 @@ class Meta:
2929
model = Pet
3030
fields = "__all__"
3131

32+
def clean_age(self):
33+
age = self.cleaned_data["age"]
34+
if age >= 99:
35+
raise ValidationError("Too old")
36+
return age
37+
3238

3339
class PetType(DjangoObjectType):
3440
class Meta:
@@ -258,6 +264,10 @@ class Mutation(ObjectType):
258264
name
259265
age
260266
}
267+
errors {
268+
field
269+
messages
270+
}
261271
}
262272
}
263273
"""
@@ -270,6 +280,42 @@ class Mutation(ObjectType):
270280
self.assertEqual(pet.name, "Mia")
271281
self.assertEqual(pet.age, 10)
272282

283+
def test_model_form_mutation_invalid_input(self):
284+
class PetMutation(DjangoModelFormMutation):
285+
pet = Field(PetType)
286+
287+
class Meta:
288+
form_class = PetForm
289+
290+
class Mutation(ObjectType):
291+
pet_mutation = PetMutation.Field()
292+
293+
schema = Schema(query=MockQuery, mutation=Mutation)
294+
295+
result = schema.execute(
296+
""" mutation PetMutation {
297+
petMutation(input: { name: "Mia", age: 99 }) {
298+
pet {
299+
name
300+
age
301+
}
302+
errors {
303+
field
304+
messages
305+
}
306+
}
307+
}
308+
"""
309+
)
310+
self.assertIs(result.errors, None)
311+
self.assertEqual(result.data["petMutation"]["pet"], None)
312+
self.assertEqual(
313+
result.data["petMutation"]["errors"],
314+
[{"field": "age", "messages": ["Too old"],}],
315+
)
316+
317+
self.assertEqual(Pet.objects.count(), 0)
318+
273319
def test_model_form_mutation_mutate_invalid_form(self):
274320
class PetMutation(DjangoModelFormMutation):
275321
class Meta:

0 commit comments

Comments
 (0)