如何在不使用表单的情况下,将使用for loop在Django模板中创建的多个复选框中的数据传递到views.py

2024-04-23 20:46:49 发布

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

这是我的html表单,其中我有一个单词的文本字段,我正在运行一个for循环,该循环为用户拥有的文档列表创建了复选框,并将其显示为表单

<body>
<form id="form" method = "POST">
    {% csrf_token %}
    <fieldset id="User">
    <legend>Your details:</legend>
        <p><label for="word">Enter your word</label>
            <input type="text" id="word" name="word">
        </p>
        {% for doc in docs %}
        <p>
            <input type="checkbox" id="{{ doc.document_id }}" name="docid" value="{{ doc.path }}">
            <label for="{{ doc.document_id }}"> {{ doc.document_name }} </label><br>
        </p>
        {% endfor%}
        <input type="submit" value="Submit" >
</fieldset>
</form>
</body>

views.py中,我有下面的方法加载这个html页面

def client_home(request):
    client_pr = Client_Profile.objects.get(user_id=request.user)
    events = Event.objects.filter(client_id=client_pr.pk)
    name = request.POST.get('word')
    id = request.POST.get('docid')
    print(name)
    print(id)
    docs = []
    for eve in events:
        docs = Document.objects.filter(event_id=eve)
    context = {'events': events, 'docs': docs}
    return render(request, 'Elasticsearch/form.html', context)

我的问题是,当我根据用户拥有的文档数量使用for-loop create checkbox字段时,当我尝试在我的Views.py文件中打印它们时,它仅优先于创建其复选框的最后一个文档id,而不是所有文档


2条回答

您需要使用^{}从复选框中获取所有选定值,因此:

id_list = request.POST.getlist('docid')

否则,使用get将只返回最后一个

通过查看您的视图,我假设您希望将特定于用户的文档列表传递给模板。当前,在for循环的每次迭代中都要覆盖docs

改变

docs = Document.objects.filter(event_id=eve)

docs += Document.objects.filter(event_id=eve)

相关问题 更多 >