Python Django检查复选框是否被选中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29714763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:55:09  来源:igfitidea点击:

Django check if checkbox is selected

pythondjangocheckbox

提问by user3496101

I'm currently working on a fairly simple django project and could use some help. Its just a simple database query front end.

我目前正在研究一个相当简单的 django 项目,可以使用一些帮助。它只是一个简单的数据库查询前端。

Currently I am stuck on refining the search using checkboxes, radio buttons etc

目前我坚持使用复选框、单选按钮等来优化搜索

The issue I'm having is figuring out how to know when a checkbox (or multiple) is selected. My code so far is as such:

我遇到的问题是弄清楚如何知道何时选择了一个复选框(或多个)。到目前为止我的代码是这样的:

views.py

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})

search.html

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

My current idea is that I check which checkboxes/radio buttons are selected and depending which are, the right data will be queried and displayed in a table.

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

So specifically: How do I check if specific check-boxes are checked? and how do I pass this information onto views.py

特别是:如何检查是否选中了特定的复选框?以及如何将这些信息传递给views.py

采纳答案by Christian Abbott

Radio Buttons:

单选按钮:

In the HTML for your radio buttons, you need all related radio inputs to share the same name, have a predefined "value" attribute, and optimally, have a surrounding label tag, like this:

在单选按钮的 HTML 中,您需要所有相关的单选输入共享相同的名称,具有预定义的“值”属性,并且最好有一个周围的标签标签,如下所示:

<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>

Then in your view, you can look up which was selected by checking for the shared "name" attribute in the POST data. It's value will be the associated "value" attribute of the HTML input tag:

然后在您的视图中,您可以通过检查 POST 数据中的共享“名称”属性来查找选择的哪个。它的值将是 HTML 输入标签的关联“值”属性:

# 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...

That works, but it requires manual checks. It's better to create a Django form first. Then Django will do those checks for you:

这有效,但它需要手动检查。最好先创建一个 Django 表单。然后 Django 会为你做这些检查:

forms.py:

表格.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)

your_template.html:

your_template.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:

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

Checkboxes:

复选框:

Checkboxes work like this:

复选框的工作方式如下:

forms.py:

表格.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)

views.py:

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

Further reading:

进一步阅读:

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

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/widgets/#radioselect

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

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

回答by vatay

In models :

在模型中:

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

In the template:

在模板中:

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

Assuming you are sending the form as a POST, the values of the selected checkboxes are in request.POST.getlist('tag').

假设您将表单作为 POST 发送,所选复选框的值位于 request.POST.getlist('tag') 中。

For example :

例如 :

<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" />

Say if 1,4 were checked,

假设如果检查了 1,4,

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

check_values will contain [1,4] (those values that were checked)

check_values 将包含 [1,4](那些被检查的值)