Django检查是否选中了复选框 [英] Django check if checkbox is selected
问题描述
目前,我使用复选框,收音机按钮等进行了精简搜索。
我遇到的问题正在弄清楚如何选择何时选中复选框(或多个)。到目前为止,我的代码是这样的:
views.py
$ b $
如果请求中有'q',则
q = request.GET ['q']
if不是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
code>< p>这是测试站点< / p>< / center>
< hr>
< center>
{%if error == true%}
< p>< font color =red>请输入有效的搜索词< / p>
{%endif%}
< form action =method =get>
< input type =textname =q>
< input type =submitvalue =Search>< br>
< / form>
< form action =method =post>
< input type ='radio'name ='locationbox'id ='l_box1'>显示位置
< input type ='radio'name ='displaybox'id ='d_box2'>显示方向
< / form>
< / center>
我目前的想法是,我检查选中了哪些复选框/单选按钮,根据哪些是正确的数据将被查询并显示在表格中。
所以具体来说:
如何检查特定的复选框是否被检查?我如何将这些信息传递给 views.py
strong> Radio Buttons:
在您的单选按钮的HTML中,您需要所有相关的无线电输入才能共享相同的名称,具有预定义的值属性,并且最佳地,有一个周围的标签标签,如下所示:
< form action =method =post >
< label for =l_box1>< input type =radioname =display_typevalue =locationboxid =l_box1>显示位置< / label>
< label for =d_box2>< input type =radioname =display_typevalue =displayboxid =d_box2>显示方向< / label>
< / form>
然后在您的视图中,您可以通过检查共享的名称属性来查找选中哪个在POST数据中。它的值将是HTML输入标签的相关值属性:
#views.py
def my_view (请求):
...
如果request.method ==POST:
display_type = request.POST.get(display_type,None)
如果display_type在[locationbox,displaybox]:
#处理这里选择的任何一个
#但是,这不是最好的方法。见下文...
这样做,但需要手动检查。最好先创建一个Django表单。那么Django会为你做这些检查:
forms.py:
从django导入表单
pre>
DISPLAY_CHOICES =(
(locationbox,显示位置),
(displaybox,显示方向)
)
class MyForm(forms.Form):
display_type = forms.ChoiceField(widget = forms.RadioSelect,choices = DISPLAY_CHOICES)
your_template.html:
< form action = method =post>
{#这将显示你的单选按钮HTML#b $ b {{form.as_p}}
{#这里需要一个提交按钮或类似的实际发送表单# }
< / form>
views.py:
from .forms import MyForm
from django.shortcuts import render
def my_view(request):
...
form = MyForm (request.POST或None)
如果request.method ==POST:
#有Django验证您的表单
如果form.is_valid():
# display_type键现在保证存在,
#保证是displaybox或locationbox
display_type = request.POST [display_type]
...
#这将显示GET请求
#的空白表单,或者显示无效的POST表单上的错误
return render(request,'your_template.html',{'form':form})
复选框:
复选框的工作方式如下:
forms.py:
类MyForm(forms.Form):
#对于BooleanFields,req uired = False意味着Django的验证
#将接受一个已检查或未检查的值,而required = True
#将验证用户必须检查该框。
something_truthy = forms.BooleanField(required = False)
views.py:
def my_view(request):
...
form = MyForm(request.POST或None)
如果request.method ==POST:
如果form.is_valid():
...
如果request.POST [something_truthy]:
#复选框被检查
...
进一步阅读: p>
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/田/#booleanfield
I'm currently working on a fairly simple django project and could use some help. Its just a simple database query front end.
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
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>
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
解决方案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:
<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:
# 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:
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})
Checkboxes:
Checkboxes work like this:
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 ...
Further reading:
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
这篇关于Django检查是否选中了复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!