| 1 | Index: /home/tobryan1/workspace/django/docs/newforms.txt
|
|---|
| 2 | ===================================================================
|
|---|
| 3 | --- /home/tobryan1/workspace/django/docs/newforms.txt (revision 5478)
|
|---|
| 4 | +++ /home/tobryan1/workspace/django/docs/newforms.txt (working copy)
|
|---|
| 5 | @@ -1617,6 +1617,28 @@
|
|---|
| 6 | this data is not bound to the form. You will need to bind data to the
|
|---|
| 7 | form before the form can be saved.
|
|---|
| 8 |
|
|---|
| 9 | +So, to edit an object already in the database, use the following pattern. In
|
|---|
| 10 | +the GET branch of your view, instantiate a form using ``form_for_instance`` and
|
|---|
| 11 | +display it on the page. In the POST branch, again use ``form_for_instance``, and
|
|---|
| 12 | +then bind the data to the form. Here's a short example:
|
|---|
| 13 | +
|
|---|
| 14 | + #typical view pattern
|
|---|
| 15 | + def edit_foo_by_id(request, foo_id):
|
|---|
| 16 | + foo = Foo.objects.get_object_or_404(id=foo_id)
|
|---|
| 17 | + FooForm = form_for_instance(foo)
|
|---|
| 18 | + if request.POST:
|
|---|
| 19 | + data = request.POST.copy()
|
|---|
| 20 | + f = FooForm(data)
|
|---|
| 21 | + if f.is_valid():
|
|---|
| 22 | + f.save()
|
|---|
| 23 | + ... #probably redirect to result page
|
|---|
| 24 | + else:
|
|---|
| 25 | + #handle validation error
|
|---|
| 26 | + else:
|
|---|
| 27 | + #GET
|
|---|
| 28 | + f = FooForm()
|
|---|
| 29 | + ... #return response and display form
|
|---|
| 30 | +
|
|---|
| 31 | When you call ``save()`` on a form created by ``form_for_instance()``,
|
|---|
| 32 | the database instance will be updated. As in ``form_for_model()``, ``save()``
|
|---|
| 33 | will raise ``ValueError`` if the data doesn't validate.
|
|---|