gpt4 book ai didi

python - 如何使用多个选择选项并使这些选项保持选中状态?

转载 作者:太空宇宙 更新时间:2023-11-03 20:27:48 25 4
gpt4 key购买 nike

使用CheckboxSelectMultiple()小部件保存数据选项后未选择表单小部件值

forms.py

class Client_ProcessForm(forms.Form):
process = forms.ModelChoiceField(queryset= Process.objects.all(), widget=forms.CheckboxSelectMultiple)

Views.py

def Edit_Client(request, id):
form = Client_ProcessForm(request.POST)
edit_record = Client.objects.get(pk=id)
obj = Client.objects.all()
cp = Client_Process.objects.filter(client_id=edit_record)
cp1 = cp.values_list('process')
obj1 = {}
for i in range(len(cp1)):
ps = Process.objects.filter(id__in=cp1[i])
print(ps)
obj1[cp1[i][0]] = list(ps)
return redirect('/client_list/')
return render(request, 'edit_client.html',{'edit_record': edit_record, 'form' : form, 'obj' : obj, 'cp' : obj1})

html

<select name="process">
{% for entry in form %}
<option value="{{ entry }}">{{ entry.process }}</option>
{% endfor %}
</select>

最佳答案

这可以通过 JavaScript 来完成。检查以下示例:

flask_test.py

from flask import Flask, request, render_template

app = Flask(__name__)
app.config['DEBUG'] = True


@app.route('/')
def index():
nl = ['option 1', 'option 5', 'option 6' ]
form = ['option 1', 'option 2', 'option 3', 'option 4', 'option 5', 'option 6']
return render_template('index.html', nl=nl, form=form)


if __name__ == "__main__":
app.run()

index.html

<html>
<body onload="runme();">
<select multiple>
{% for entry in form %}
<option value="{{ entry }}">{{ entry }}</option>
{% endfor %}
</select>

</body>
<script>
function runme() {
var nl = [];
var options = document.getElementsByTagName('select')[0].options;
{% for vl in nl %}
nl.push('{{vl}}');
{% endfor %}
for (i=0;i<options.length;i++){
for (j=0;j<nl.length;j++){
if (options[i].value == nl[j]){
options[i].selected = 'selected';
}
}
}
};
</script>
</html>

关于python - 如何使用多个选择选项并使这些选项保持选中状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57703082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com