Ticket #4572: form_for_instance.patch

File form_for_instance.patch, 1.4 KB (added by anonymous, 17 years ago)
  • home/tobryan1/workspace/django/docs/newforms.txt

     
    16171617this data is not bound to the form. You will need to bind data to the
    16181618form before the form can be saved.
    16191619
     1620So, to edit an object already in the database, use the following pattern. Get
     1621the 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,
     1623instantiate the class with no data, and it will use the values from the
     1624instance as defaults. In the POST branch, instantiate the form using the POST
     1625data 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                       
    16201644When you call ``save()`` on a form created by ``form_for_instance()``,
    16211645the database instance will be updated. As in ``form_for_model()``, ``save()``
    16221646will raise ``ValueError`` if the data doesn't validate.
Back to Top