web-dev-qa-db-ja.com

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に渡す方法

10
user3496101

ラジオボタン:

ラジオボタンの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>

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

19

モデルで:

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](チェックされた値)が含まれます

7
vatay