django - post form on select

2019-01-23 18:43发布

I made a simple django form, with a list of choices (in radio buttons):

class MyForm(forms.Form):
            choices=forms.ChoiceField( widget=forms.RadioSelect(), choices=[(k,k) for k in ['one','two','three']],label="choose one")

I would like the form to submit automatically when a user selects one of the options. In straightforward HTML I would've done it as

  <select name='myselect' onChange="FORM_NAME.submit();">
    ....
  </select>

But I do not know how to integrate this into the form class without writing a template. Specifically, I would need to know FORM_NAME so I can call FORM_NAME.submit() in the above snippet. Can it be done without using a template?

1条回答
神经病院院长
2楼-- · 2019-01-23 19:12

I think you do not need to know the form name. This should work as well:

<select name='myselect' onChange="this.form.submit();">

A quick solution to integrate this into your form would involve adding a attribute to your widget.

widget=forms.RadioSelect(attrs={'onchange': 'this.form.submit();'})

Now one could argue if this isn't better separated from your form definition (separating definition, style and behaviour), but that should do it.

查看更多
登录 后发表回答