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

2024-06-06 17:28:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

表单.py

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

视图.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>

Tags: formclientidobjobjectsrequestformsrecord
1条回答
网友
1楼 · 发布于 2024-06-06 17:28:11

这可以通过javascript实现。检查以下示例:

烧瓶试验.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()

索引.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>

相关问题 更多 >