【问题标题】:Django. How to get value from multiple checkboxes姜戈。如何从多个复选框中获取值
【发布时间】:2022-01-22 09:23:28
【问题描述】:

嘿,我看到了很多关于这个的问题,但我不知道为什么它不适合我。我的home.html 文件中有这段代码:

<form action="/result/" method="post">
<div class="form-locat-att">
    {% csrf_token %}
    Location: <input type="text" name="location_input" required/>
    <p></p><br>
    <button class="btn btn-block btn-round", name="search_button">Search</button>
    <p></p>

    <h5>Zabytki</h5> <p></p>
    <input type="checkbox" id="museum" name="att[]" value=" Museum OR">
    <label for="muzeum"> Museum</label> &nbsp;

    <input type="checkbox" id="statue" name="att[]" value=" Statue OR">
    <label for="pomnik"> Statue</label> &nbsp;

    <input type="checkbox" id="castle" name="att[]" value=" Castle OR">
    <label for="zamek"> Castle</label> &nbsp;

    <input type="checkbox" id="palace" name="att[]" value=" Palace OR">
    <label for="palac"> Palace</label> <p></p>

</div>
</form>

这是我的views.py

def result(request):
    if request.method == 'POST' and 'search_button' in request.POST:

        attrac = request.POST.getlist('att[]')
        locat = request.POST.get('location_input')

        print(attrac)

        # (here i have some irrelevant code where i render my context)
        return render(request, 'przewodnik_app/result.html', context)
    return render(request, 'przewodnik_app/result.html')

我正在尝试打印attrac,它应该为我提供我选中的复选框中的值。例如,当我使用带有 id 的 .get 方法时 request.POST.get('博物馆') 它返回正确的值。当我使用name 时,列表始终为空。

【问题讨论】:

    标签: django post checkbox


    【解决方案1】:

    您的代码对我来说似乎工作正常,打印出来:

    # print(request.POST) prints out
    <QueryDict: {'csrfmiddlewaretoken': ['ty1QJh1jQpwt1Bgd77lLJqyudgSLt5wGCx4zSfh9Iwak02A4J8JiliMHPZa034v6'], 'location_input': ['Holland'], 'search_button': [''], 'att[]': [' Museum OR', ' Castle OR', ' Palace OR']}>
            
    # request.POST.getlist('att[]') prints out
    [' Museum OR', ' Castle OR', ' Palace OR']
    

    你也不需要if request.method == 'POST' and 'search_button' in request.POST:

    默认情况下,没有类型的按钮是提交按钮,在&lt;form&gt; 标签内提交带有name 属性的所有内容(但你应该给它一个类型),所以不要

    &lt;button class="btn btn-block btn-round", name="search_button"&gt;Search&lt;/button&gt;

    你应该这样做

    &lt;button class="btn btn-block btn-round", type='submit'&gt;Search&lt;/button&gt;

    然后只是if request.method == 'POST':

    【讨论】:

      猜你喜欢
      • 2017-09-19
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-11
      • 2023-03-22
      • 2018-06-20
      相关资源
      最近更新 更多