1

我有一个动态表单向导步骤如下:

class AltaForm6(forms.Form):
CHOICES = ((1, 1,), (2, 2,))

username = ChoiceFieldInvalid(required=True, label="Usuario", widget=forms.RadioSelect, choices=CHOICES)
username2 = forms.CharField(required=False, label="Otro")
#username = ChoiceWithOtherField(required=True, label="Usuario", choices=CHOICES)

def clean_username2(self):
  username = self.cleaned_data.get('username')
  username2 = self.cleaned_data.get('username2')

  if username == "Otro" and len(username2) == 0:
    raise forms.ValidationError("Debe especificar un nombre de usuario")
  return username2

def clean_username(self):
  username = self.cleaned_data.get('username')
  return username

然后我动态更改选择值:

class AltaWizard(SessionWizardView):

template_name = 'agroshare/wizard.html'

def get_form(self, step=None, data=None, files=None):
    form = super(AltaWizard, self).get_form(step, data, files)
    if step == '5':

       import logging
       logger = logging.getLogger(__name__)

       cleaned_data = self.get_cleaned_data_for_step('2') or {}
       logger.error(cleaned_data)
       nombre = cleaned_data.get('nombre')
       apellido = cleaned_data.get('apellido')

       first = possibleUid(nombre, apellido, '1')
       second = possibleUid(nombre, apellido, '2')

       if ' ' in nombre:
          third = possibleUid(nombre, apellido, '3')
          form.fields['username'].choices = ((first, first,), (second, second,), (third, third,), ("Otro", "Otro",))
       if ' ' in apellido:
          fourth = possibleUid(nombre, apellido, '4')
          form.fields['username'].choices = ((first, first,), (second, second,), (fourth, fourth,), ("Otro", "Otro",))
       else:
          form.fields['username'].choices = ((first, first,), (second, second,), ("Otro", "Otro",))
    if step == '5':
       form.user = self.request.user
    return form

    def render(self, form=None, **kwargs):
    form = form or self.get_form()
    context = self.get_context_data(form=form, **kwargs)
    if self.steps.current == '5':
       form2 = self.get_form('5')
       cleaned_data = self.get_cleaned_data_for_step('5') or {}
       username = cleaned_data.get('username')
       form2.fields['username'].choices = [username]
    return self.render_to_response(context)

问题是,当我通过向导返回此步骤时,它不会修改“选择”值,而是显示“CHOICES = ((1, 1,), (2, 2,))”

当我回到这一步时,我怎样才能做到这一点,表单实际上可以显示我想要的值?

4

0 回答 0