Django检查是否选中了复选框

时间:2015-04-18 08:20:24

标签: python django checkbox

我目前正在开发一个相当简单的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})

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

3 个答案:

答案 0 :(得分:19)

收音机按钮:

在单选按钮的HTML中,您需要所有相关的无线电输入共享相同的名称,具有预定义的&#34;值&#34;属性,并且最佳地,有一个周围的标签标签,如下所示:

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

然后在您的视图中,您可以通过检查共享&#34;名称&#34;来查找已选择的内容。 POST数据中的属性。它的价值将是相关的&#34;价值&#34; 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...

这有效,但需要人工检查。最好先创建一个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)

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:

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)

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

答案 1 :(得分:6)

在模特中:

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 :(得分: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" />