django - post form on select

徘徊边缘 提交于 2020-01-01 03:09:10

问题


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:


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.



来源:https://stackoverflow.com/questions/4934839/django-post-form-on-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!