Skip to content

Commit 5072464

Browse files
author
Grant McConnaughey
committed
Document form mutations
1 parent 4f904f4 commit 5072464

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

docs/form-mutations.rst

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
Integration with Django forms
2+
=============================
3+
4+
Graphene-Django comes with mutation classes that will convert the fields on Django forms into inputs on a mutation.
5+
6+
FormMutation
7+
------------
8+
9+
.. code:: python
10+
11+
class MyForm(forms.Form):
12+
name = forms.CharField()
13+
14+
class MyMutation(FormMutation):
15+
class Meta:
16+
form_class = MyForm
17+
18+
``MyMutation`` will automatically receive an ``input`` argument. This argument should be a ``dict`` where the key is ``name`` and the value is a string.
19+
20+
ModelFormMutation
21+
-----------------
22+
23+
``ModelFormMutation`` will pull the fields from a ``ModelForm``.
24+
25+
.. code:: python
26+
27+
class Pet(models.Model):
28+
name = models.CharField()
29+
30+
class PetForm(forms.ModelForm):
31+
class Meta:
32+
model = Pet
33+
fields = ('name',)
34+
35+
# This will get returned when the mutation completes successfully
36+
class PetType(DjangoObjectType):
37+
class Meta:
38+
model = Pet
39+
40+
class PetMutation(ModelFormMutation):
41+
class Meta:
42+
form_class = PetForm
43+
44+
``PetMutation`` will grab the fields from ``PetForm`` and turn them into inputs. If the form is valid then the mutation
45+
will lookup the ``DjangoObjectType`` for the ``Pet`` model and return that under the key ``pet``. Otherwise it will
46+
return a list of errors.
47+
48+
You can change the input name (default is ``input``) and the return field name (default is the model name lowercase).
49+
50+
.. code:: python
51+
52+
class PetMutation(ModelFormMutation):
53+
class Meta:
54+
form_class = PetForm
55+
input_field_name = 'data'
56+
return_field_name = 'my_pet'
57+
58+
Form validation
59+
---------------
60+
61+
Form mutations will call ``is_valid()`` on your forms.
62+
63+
If the form is valid then ``perform_mutate(form, info)`` is called on the mutation. Override this method to change how
64+
the form is saved or to return a different Graphene object type.
65+
66+
If the form is *not* valid then a list of errors will be returned. These errors have two fields: ``field``, a string
67+
containing the name of the invalid form field, and ``messages``, a list of strings with the validation messages.

docs/index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,5 @@ Contents:
1212
authorization
1313
debug
1414
rest-framework
15+
form-mutations
1516
introspection

0 commit comments

Comments
 (0)