Django 在改变时提交表单

6 投票
2 回答
8376 浏览
提问于 2025-04-18 07:59

你好,我正在尝试在选择一个ChoiceField选项时提交一个表单。

class ActionForm(forms.Form):
    """ Holds the options for mailbox management """
    choices = ['create new folder', 'delete', 'read', 'unread']
    action = forms.ChoiceField(choices=choices, attrs={'onchange': 'actionform.submit();'})

但是现在当我尝试加载这个表单时,出现了无效的语法错误。我很确定attrs={'onchange': 'actionform.submit();'})这一部分有问题,但我不太确定该怎么做才能解决。

2 个回答

0

在模板的 HTML 文件中的表单标签里,加入这个属性:

onchange="functionName()” to call:

function functionName(){
   var submitButton = 
document.getElementById(“the id of the button”);
   submitButton.click();
}

给提交按钮一个 ID,比如:

input type="submit" value="Submit" id="myButton"

用 CSS 设置按钮的可见性为:

#myButton{
   visibility: hidden;
}
9

你需要在字段上设置一个 widget 参数,并传入 attrs 参数:

action = forms.ChoiceField(choices=choices, 
                           widget=forms.Select(attrs={'onchange': 'actionform.submit();'}))

另外,choices 列表应该包含两个部分的内容:

choices = [(0, 'create new folder'), (1, 'delete'), (2, 'read'), (3, 'unread')]

撰写回答