@@ -29,6 +29,67 @@ class AuthorForm(AsyncModelForm):
29
29
fields = (" name" ,)
30
30
```
31
31
32
+ #### Construction
33
+
34
+ normally you instantiate a field like this:
35
+ ` form = AuthorForm(data) `
36
+ and that works fine
37
+
38
+ but sometimes you pass in an instance to the form (e.g: you are building an update view)
39
+ ``` pycon
40
+ >>> author = Author.objects.get(pk = 1 )
41
+ >>> form = AuthorForm(instance = author)
42
+ ```
43
+
44
+ in this case, you will probably face an error saying you can't do synchronous operations in an async environment
45
+ for situations like this, we provide an alternative contractor called ` from_async() `
46
+
47
+ ``` pycon
48
+ author = await Author.objects.aget(pk=1)
49
+ form = await AuthorForm.from_async(instance=author)
50
+ ```
51
+
52
+ note that ` from_async() ` is an async method that should be ` await ` ed
53
+
54
+ #### validation
55
+ if a validator requires database access (e.g: unique validator) you will face a problem in async views
56
+ to solve that, we provide a few methods
57
+
58
+ * ais_valid
59
+ ``` python
60
+ if await form.ais_valid():
61
+ # handle data
62
+ ```
63
+ an awaitable version of django's [ Form.is_valid] ( https://docs.djangoproject.com/en/5.1/ref/forms/api/#django.forms.Form.is_valid )
64
+
65
+ * aerrors (property)
66
+ ``` pycon
67
+ >>> errors = await form.aerrors
68
+ ```
69
+ an awaitable version of django's [ Form.errors] ( https://docs.djangoproject.com/en/5.1/ref/forms/api/#django.forms.Form.errors )
70
+
71
+ * afull_clean
72
+ ``` python
73
+ await form.afull_clean()
74
+ ```
75
+ an awaitable version of django's ` Form.full_clean ` , you typically don't call this manually.
76
+
77
+
78
+
79
+ #### Manual form rendering
80
+ django's templating system is fully sync, so you can't call async methods and functions in the templates
81
+ you can call sync methods and render the page using ` asgiref.sync.sync_to_async ` , or you can gather the data in your view and pass them in as context.
82
+
83
+ a few methods have been provided so forms can be rendered manually:
84
+
85
+ 1 . arender: an ` await ` able version of django's [ Form.render] ( https://docs.djangoproject.com/en/5.1/ref/forms/api/#render )
86
+ 2 . aas_div: an ` await ` able version of django's [ Form.as_div] ( https://docs.djangoproject.com/en/5.1/ref/forms/api/#as-div )
87
+ 3 . aas_p: an ` await ` able version of django's [ Form.as_p] ( https://docs.djangoproject.com/en/5.1/ref/forms/api/#django.forms.Form.as_p )
88
+ 4 . aas_ul: an ` await ` able version of django's [ Form.as_ul] ( https://docs.djangoproject.com/en/5.1/ref/forms/api/#as-ul )
89
+ 5 . aas_table: an ` await ` able version of django's [ Form.as_table] ( https://docs.djangoproject.com/en/5.1/ref/forms/api/#as-table )
90
+
91
+
92
+ note that the sync versions are still available.
32
93
33
94
___
34
95
** WARNING!**
0 commit comments