Django如何检查复选框是否被选中

16

我目前正在开发一个相当简单的django项目,需要帮助。它只是一个简单的数据库查询前端。

目前,我遇到了使用复选框、单选按钮等来精细化搜索的问题。

我面临的问题是如何知道何时选择了一个或多个复选框。到目前为止,我的代码如下:

views.py

def search(request):
    if 'q' in request.GET:
        q = request.GET['q']
        if not q:
            error = True;
        elif len(q) > 22:
            error = True;
        else:           
            sequence = Targets.objects.filter(gene__icontains=q)
            request.session[key] = pickle.dumps(sequence.query)
            return render(request, 'result.html', {'sequence' : sequence, 'query' : q, 'error' : False})    
    return render(request, 'search.html', {'error': True})

搜索.html

<p>This is a test site</p></center>

        <hr>
        <center>
            {% if error == true %}
                <p><font color="red">Please enter a valid search term</p>
            {% endif %}
         <form action="" method="get">
            <input type="text" name="q">
            <input type="submit" value="Search"><br>            
         </form>
         <form action="" method="post">
            <input type='radio' name='locationbox' id='l_box1'> Display Location
            <input type='radio' name='displaybox' id='d_box2'> Display Direction
         </form>
        </center>

我目前的想法是,检查哪些复选框/单选按钮被选中,根据选中情况查询正确的数据并在表格中显示。

具体来说: 如何检查特定的复选框是否已被选中?如何将此信息传递给 views.py


你无法在客户端的网页浏览器上执行Python代码,因此你需要使用JavaScript来实现。 - Vaibhav Sagar
3个回答

28

单选按钮:

在单选按钮的 HTML 中,你需要让所有相关的单选输入框分享同一个名称,并且有一个预定义的“value”属性,最好还要有一个包围它们的 label 标签,像这样:

<form action="" method="post">
    <label for="l_box1"><input type="radio" name="display_type" value="locationbox" id="l_box1">Display Location</label>
    <label for="d_box2"><input type="radio" name="display_type" value="displaybox" id="d_box2"> Display Direction</label>
</form>

那么在你的观点中,你可以通过检查POST数据中共享的"name"属性来查找被选中的选项。它的值将是HTML输入标签关联的"value"属性:

然后,在您的观点中,您可以通过检查POST数据中共享的"name"属性来查找所选项目。 它的值将是与HTML输入标记相关联的"value"属性:

# views.py
def my_view(request):
    ...
    if request.method == "POST":
        display_type = request.POST.get("display_type", None)
        if display_type in ["locationbox", "displaybox"]:
            # Handle whichever was selected here
            # But, this is not the best way to do it.  See below...

那样做是可行的,但需要手动检查。最好先创建一个 Django 表单,然后 Django 会为您执行这些检查:

forms.py:

from django import forms

DISPLAY_CHOICES = (
    ("locationbox", "Display Location"),
    ("displaybox", "Display Direction")
)

class MyForm(forms.Form):
    display_type = forms.ChoiceField(widget=forms.RadioSelect, choices=DISPLAY_CHOICES)

您的模板.html:

<form action="" method="post">
    {# This will display the radio button HTML for you #}
    {{ form.as_p }}
    {# You'll need a submit button or similar here to actually send the form #}
</form>

视图函数文件:views.py

from .forms import MyForm
from django.shortcuts import render

def my_view(request):
    ...
    form = MyForm(request.POST or None)
    if request.method == "POST":
        # Have Django validate the form for you
        if form.is_valid():
            # The "display_type" key is now guaranteed to exist and
            # guaranteed to be "displaybox" or "locationbox"
            display_type = request.POST["display_type"]
            ...
    # This will display the blank form for a GET request
    # or show the errors on a POSTed form that was invalid
    return render(request, 'your_template.html', {'form': form})

多选框:

多选框的工作方式如下:

forms.py:

class MyForm(forms.Form):
    # For BooleanFields, required=False means that Django's validation
    # will accept a checked or unchecked value, while required=True
    # will validate that the user MUST check the box.
    something_truthy = forms.BooleanField(required=False)

视图.py:

def my_view(request):
    ...
    form = MyForm(request.POST or None)
    if request.method == "POST":
        if form.is_valid():
            ...
            if request.POST["something_truthy"]:
                # Checkbox was checked
                ...

进一步阅读:

https://docs.djangoproject.com/en/1.8/ref/forms/fields/#choicefield

https://docs.djangoproject.com/en/1.8/ref/forms/widgets/#radioselect

https://docs.djangoproject.com/en/1.8/ref/forms/fields/#booleanfield


非常感谢你的回复。我想我得去使用复选框方法。但是我有点不理解如何使用它。在你的第三个嵌套IF语句之后,我该如何检查哪些复选框被使用了呢?再次感谢你的回复,请原谅我对Django还很新 :)。 - user3496101
在复选框示例中,MyForm 渲染了一个带有标签“Something truthy”的复选框。在 my_view() 中,如果该复选框被选中,则 request.POST["something_truthy"] 为 True,否则为 False。 - Christian Abbott
谢谢回复!我现在明白这部分了 :) 不过我还有一个后续问题,如果您能给我一些建议就好了。我已经修改了原帖。我的问题是关于筛选特定列,因为我在谷歌上搜索了一下,没有找到我想要的内容。再次感谢! - user3496101
你应该从这个问题中删除你的后续问题,并将其作为一个单独的问题。Stackoverflow旨在提供一个特定问题对应一个特定答案,而不是关于某个主题的持续帮助。如果这个答案满足了你最初的问题,你应该将其标记为“接受”,以便其他有类似问题的人可以轻松找到它。 - Christian Abbott
我已经为了清晰起见,去掉了这个问题文本中的后续问题。如果您需要参考它,可以在问题的修订历史中找到它。 - Christian Abbott

11

在模型中:

class Tag:
    published = BooleanField()
    (...)

在模板中:

{% for tag in tags %}
<label class="checkbox">
    <input type="checkbox" name="tag[]" value="" {% if tag.published %}checked{% endif %}>
</label>
{% endfor %}
假设您正在将表单作为POST发送,选中复选框的值在request.POST.getlist('tag')中。
例如:
<input type="checkbox" name="tag[]" value="1" />
<input type="checkbox" name="tag[]" value="2" />
<input type="checkbox" name="tag[]" value="3" />
<input type="checkbox" name="tag[]" value="4" />

如果1和4被选择了,那么请说出来。

check_values = request.POST.getlist('tag')

check_values将包含[1,4](已选中的值)


2
这个答案仅适用于与表单相关联的模型,而在所提出的问题中并非如此。 - Christian Abbott

1
{% for tag in tags %}
<label class="checkbox">
    <input type="checkbox" name="tag[]" value="" 
{% if tag.published %}checked{% endif %}>
</label>
{% endfor %}

<input type="checkbox" name="tag[]" value="1" />
<input type="checkbox" name="tag[]" value="2" />
<input type="checkbox" name="tag[]" value="3" />
<input type="checkbox" name="tag[]" value="4" />

1
请不要只发代码作为答案,还请提供代码解决问题的方法和原理。附带解释的答案通常更有帮助、质量更好,并且更可能吸引赞同。 - Ran Marciano

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接