Skip to content

Commit 481d3ff

Browse files
authored
Fix DjangoModelFormMutation (#915)
* Fix DjangoModelFormMutation * Try and fix tests * Remove unused form
1 parent 9d9a14c commit 481d3ff

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:
@@ -243,6 +249,10 @@ class Mutation(ObjectType):
243249
name
244250
age
245251
}
252+
errors {
253+
field
254+
messages
255+
}
246256
}
247257
}
248258
"""
@@ -255,6 +265,42 @@ class Mutation(ObjectType):
255265
self.assertEqual(pet.name, "Mia")
256266
self.assertEqual(pet.age, 10)
257267

268+
def test_model_form_mutation_invalid_input(self):
269+
class PetMutation(DjangoModelFormMutation):
270+
pet = Field(PetType)
271+
272+
class Meta:
273+
form_class = PetForm
274+
275+
class Mutation(ObjectType):
276+
pet_mutation = PetMutation.Field()
277+
278+
schema = Schema(query=MockQuery, mutation=Mutation)
279+
280+
result = schema.execute(
281+
""" mutation PetMutation {
282+
petMutation(input: { name: "Mia", age: 99 }) {
283+
pet {
284+
name
285+
age
286+
}
287+
errors {
288+
field
289+
messages
290+
}
291+
}
292+
}
293+
"""
294+
)
295+
self.assertIs(result.errors, None)
296+
self.assertEqual(result.data["petMutation"]["pet"], None)
297+
self.assertEqual(
298+
result.data["petMutation"]["errors"],
299+
[{"field": "age", "messages": ["Too old"],}],
300+
)
301+
302+
self.assertEqual(Pet.objects.count(), 0)
303+
258304
def test_model_form_mutation_mutate_invalid_form(self):
259305
class PetMutation(DjangoModelFormMutation):
260306
class Meta:

0 commit comments

Comments
 (0)