| 1620 | So, to edit an object already in the database, use the following pattern. Get |
| 1621 | the object for which you want to create a form in and use the |
| 1622 | `form_for_instance` function to create a Form class. In the GET branch, |
| 1623 | instantiate the class with no data, and it will use the values from the |
| 1624 | instance as defaults. In the POST branch, instantiate the form using the POST |
| 1625 | data and these will be saved to the database. Here's a short example: |
| 1626 | |
| 1627 | #typical view pattern |
| 1628 | def edit_foo_by_id(request, foo_id): |
| 1629 | foo = get_object_or_404(Foo, id=foo_id) |
| 1630 | FooForm = form_for_instance(foo) |
| 1631 | if request.method == 'POST': |
| 1632 | data = request.POST.copy() |
| 1633 | f = FooForm(data) |
| 1634 | if f.is_valid(): |
| 1635 | f.save() |
| 1636 | ... #probably redirect to result page |
| 1637 | else: |
| 1638 | #handle validation error |
| 1639 | else: |
| 1640 | #GET |
| 1641 | f = FooForm() |
| 1642 | ... #return response and display form |
| 1643 | |