django-merlin icon indicating copy to clipboard operation
django-merlin copied to clipboard

How to set a dynamically added form's initial data based on a previously submitted form?

Open stodge opened this issue 13 years ago • 1 comments

I created a wizard with one form. When the user submits that form, I add another step dynamically based on the user's submitted data. When the user submits this new form I want to add another step, which I can do. But how do I set initial data in that third form based on the user's data submitted in the second form? I realise this sounds complicated, so here's a simple example:

class SelectTypeForm(forms.Form):
    content_type = forms.ChoiceField(choices=build_content_types(), label='Select content type')

class EnterTitleForm(forms.Form):
    title = forms.CharField(max_length=128)

class EnterDescriptionForm(forms.Form):
    description = forms.CharField(max_length=128)

When the user submits the EnterTitleForm I want to set an initial value for the description field in the last form based on the user's input. For example, if the user enters a title of 'hello' I want to set the description to 'welcome'.

It's a trivial nonsensical example but hopefully it clarifies my question.

Thanks

stodge avatar Jun 03 '11 14:06 stodge

This is an interesting case. There is not a real clean way to do this in the SessionWizard. There are so different strategies you can use.

  1. You store the initial data in the wizard's form_data dictionary before you go to the next step
  2. You could override get_cleaned_data and provide the initial data for a step but you would have to take in account whether it was a POST or GET request.
  3. You could override process_GET to handle this case.

Most of these a hacky in my view. This might be a good feature request to add to the SessionWizard but:

  1. I think the most interesting would be to use the initial parameter on the Form field. This parameter is used for this very purpose to allow a non-bound form to have initial data for rendering and it does not trigger validation. It does not have to be a hard coded value either, you can point it to a callable. The Form has the same parameter but I am not sure if you can set it after form creation since process_GET creates the Form. If you can, which I will dig and try to find, you could set this initial data for the Form in process_show_form method which is a hook that is meant to be overridden.

Let me know what you try and I will see if I can think of some more ways or how this could be included as a feature.

supercodepoet avatar Jun 03 '11 14:06 supercodepoet