views:

741

answers:

2

A simple form with ModelChoiceField displayed as radio buttons (the inherited widget).

I'm using an onchange event to POST, everytime a user selects a radio button:

shipping_choice = ShippingChoiceField(
 queryset=ShippingMethods.objects.all(),
 empty_label=None,
 widget=forms.RadioSelect(attrs={
  'class': 'order',
  'onchange': '$("#shipping_choice").submit()',
 })
)

I need to have the radio that the user selected thought, actually be "selected" when the page reloads.

Adding an extra attr 'selected', will not do, 'cause it needs to happen when the user actually has made a choice first.

+1  A: 

Forms have an initial attribute which you can use:

form = YourForm(initial={'shipping_choice': current_choice})

Then again, I'm guessing you are using a ModelForm, in which case you should just be passing the instance:

form = YourForm(instance=order)   # where "order" is your instance...

Or maybe you just don't understand that a form can be bound to data:

if request.method == 'POST':
    order_form = YourForm(data=request.POST)
else:
    order_form = YourForm()
SmileyChris
Hey mate,No, I'm not using a ModelForm, this is a pre-check form, that just checks up to set a shipping_method (the order is created on the next step, 'cause all info is in the session).I'm not sure initial will do the trick, 'cause isn't it intended just for initial display? Can it be set dynamically each time a user picks a different radio, and the form resubmits?
panosl
Also, not sure how to set the current_choice, since I have to instantiate the form to get the submitted value.
panosl
I edited my answer to include a section on how you bind a form to data. Without trying to sound patronising, have you read http://docs.djangoproject.com/en/dev/ref/forms/api/#ref-forms-api ?
SmileyChris
A: 

Your question and subsequent comment aren't clear, unfortunately. What do you mean by displaying it 'when the form resubmits'?

Usually the flow is display the form, submit, redisplay it if there are any errors, then proceed to a confirmation page. At what point are you having problems? Or is your flow significantly differet form this?

Daniel Roseman
Sorry if it was unclear. The form displays a radio list of shipping_options. These vary depending on the customer's country. This filtering happens in the __init__ of the form. The submit only takes place, the recalculation can take place, and display the new total to the user, that's why I am calling submit on the "onchange" event.This works fine, except the radio that was actually selected, is not displayed like so (selected), when the view returns (the view processes the form and redisplays it).
panosl