django - 选择后的表单 [英] django - post form on select

查看:149
本文介绍了django - 选择后的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的django表单,其中列出了选项(单选按钮):

  class MyForm(forms。表单):
choices = forms.ChoiceField(widget = forms.RadioSelect(),choices = [(k,k)for [in','two','three']],label =选择一个)

当用户选择其中一个选项时,我希望表单自动提交。在简单的HTML中,我将这样做为

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

但是我不知道如何将它整合到表单类中,而无需编写模板。具体来说,我需要知道 FORM_NAME ,所以我可以在上述代码段中调用 FORM_NAME.submit()
可以不使用模板吗?

解决方案

我想你不需要知道表单名称。这也应该是有效的:

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

将一个快速的解决方案整合到您的表单中将涉及添加属性到您的小部件

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

现在可以争论,如果这不是更好地与您的表单定义分离(分离定义,样式和行为),但应该这样做。 >

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?

解决方案

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.

这篇关于django - 选择后的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆