16

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

1
  • You can't execute Python on the client's web browser and so you will need to use JavaScript for this. Commented Apr 18, 2015 at 8:27

3 Answers 3

28

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

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks a lot for the reply. I think I'm going to have to work with the checkboxe method. But I'm having a little understanding how to use it. After your third nested IF statement, how exactly do I go about checking which of the checkboxes are used? Thanks again for the reply, and please bear wuth me as I'm new to django :)
In the checkbox example, MyForm renders a checkbox with the label "Something truthy". In my_view(), request.POST["something_truthy"] is True if that checkbox was checked, and False if not.
Thanks for the reply! I understand this portion now :) I also have follow up question though if you could maybe give me some advice. I have emended the original post. My question is about filtering specific columns as I've searched for this on google and cannot find what I'm looking for. Thanks again!
You should remove your follow-up question from this question and make that its own separate question. Stackoverflow is designed for one-specific-question >>> one-specific-answer, rather than ongoing help on a topic. If this answer satisfies your original question, you should mark it as "accepted" so others with similar questions can find it easily.
I went ahead and took the liberty of removing the follow-up question from this question's text for clarity. If you need to refer to it, you can access it in the question's revision history.
11

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').

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,

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

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

1 Comment

This answer is only applicable when there's a model associated with the form, which isn't the case in the question that was asked.
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" />

1 Comment

Please don't post only code as an answer, but also provide an explanation of what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.