pombreda / formalchemy

Automatically exported from code.google.com/p/formalchemy
MIT License
0 stars 0 forks source link

After syncing form, selected property in select tag is lost #104

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
So, here is my case:

Step 1:
I create a form for a model containing a foreign key to a second model. I
render it and the result is as expected: I get a select tag populated with
the instances of the second model, and the current foreign key is marked as
"selected".

Step 2:
I update some fields from my form (I don't touch the select one) and submit
it. In my Django view I sync the form and commit the model instance
updates. Something like this:

def get_and_update_thing(request, id):
    # sqlalchemy session is provided by the request
    s = request.sa_session
    thing = s.query(Thing).filter(Thing.id==id).one()
    # the form has been previously configured, nothing special
    form = thing_form.bind(thing, data=request.POST or None)
    if request.POST and form.validate():
        form.sync()
        s.add(thing)
        s.commit()
    return render_to_response(...)

The updates are correctly saved to the database and everything is cool.

Step 3:
I render the form again, in the same view. And then something weird
happens: everything is correct, except for the "selected" property of the
select field, which is gone. No field is selected.

I've been following FormsAlchemy code to find at which point the selected
property is "lost". That's what I've found in helpers.py (options_for_select):

 * The first time the form is rendered, the foreign model instances ids are
integers as well as the current foreign key value, so the match works and
the selected property is added.

 * After syncing the form and rendering it again, the foreign model
instances ids are still integers, but the current foreign key value is now
a string (I guess the values coming from my post are treated as strings by
FormAlchemy, but I haven't looked at it), and then the the match fails.

I've fixed it by casting both foreign models ids and current foreign key to
strings so the match works in any situation (see the patch). Casting to int
was another option, but in cases where non-numerical foreign keys are used
it wouldn't work.

Original issue reported on code.google.com by aitorc...@gmail.com on 5 Jun 2009 at 11:42

Attachments:

GoogleCodeExporter commented 9 years ago
Can you include a test case that fails before your patch?

Original comment by jbel...@gmail.com on 16 Jun 2009 at 5:12