2015-04-18 229 views
5

我目前正在研究一個相當簡單的django項目,並且可以使用一些幫助。它只是一個簡單的數據庫查詢前端。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

+0

你不能在客戶端的Web瀏覽器執行Python,所以你需要使用JavaScript來此。 –

回答

14

無線電按鈕:

在您的收音機的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> 

那麼在你看來,你可以看一下這是通過檢查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... 

這樣的工作,但它需要手動檢查。首先創建一個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> 

意見。潘岳:

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

+0

非常感謝回覆。我想我將不得不使用checkboxe方法。但我有一點點了解如何使用它。在你的第三個嵌套IF語句之後,我該如何去檢查使用哪個複選框?再次感謝您的答覆,並請忍受我,因爲我是新的django :) – user3496101

+0

在複選框示例中,MyForm呈現一個複選框,標籤爲「Something truthy」。在my_view()中,如果複選框被選中,request.POST [「something_truthy」]爲True,否則爲False。 –

+0

感謝您的回覆!我現在瞭解這部分:)我也有跟進問題,但如果你可以給我一些建議。我修改了原帖。我的問題是關於過濾特定的列,因爲我在谷歌搜索這個,並找不到我在找什麼。再次感謝! – user3496101

5

在車型:

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

此答案僅適用於存在與表單關聯的模型時,問題中並非如此。 –

相關問題