Ticket #4572: form_for_instance_patch.2.txt

File form_for_instance_patch.2.txt, 1.7 KB (added by toddobryan@…, 17 years ago)

patch to clarify how to use form_for_instance

Line 
1
2Property changes on: /home/tobryan1/workspace/django
3___________________________________________________________________
4Name: svn:ignore
5 - build
6dist
7*.egg-info
8MANIFEST
9
10 + build
11dist
12*.egg-info
13MANIFEST
14.project
15.pydevproject
16
17
18Index: /home/tobryan1/workspace/django/docs/newforms.txt
19===================================================================
20--- /home/tobryan1/workspace/django/docs/newforms.txt (revision 5595)
21+++ /home/tobryan1/workspace/django/docs/newforms.txt (working copy)
22@@ -1617,6 +1617,30 @@
23 this data is not bound to the form. You will need to bind data to the
24 form before the form can be saved.
25
26+So, to edit an object already in the database, use the following pattern. Get
27+the object for which you want to create a form in and use the
28+`form_for_instance` function to create a Form class. In the GET branch,
29+instantiate the class with no data, and it will use the values from the
30+instance as defaults. In the POST branch, instantiate the form using the POST
31+data and these will be saved to the database. Here's a short example:
32+
33+ #typical view pattern
34+ def edit_foo_by_id(request, foo_id):
35+ foo = Foo.objects.get_object_or_404(id=foo_id)
36+ FooForm = form_for_instance(foo)
37+ if request.POST:
38+ data = request.POST.copy()
39+ f = FooForm(data)
40+ if f.is_valid():
41+ f.save()
42+ ... #probably redirect to result page
43+ else:
44+ #handle validation error
45+ else:
46+ #GET
47+ f = FooForm()
48+ ... #return response and display form
49+
50 When you call ``save()`` on a form created by ``form_for_instance()``,
51 the database instance will be updated. As in ``form_for_model()``, ``save()``
52 will raise ``ValueError`` if the data doesn't validate.
Back to Top