LucasBorges-Santos
LucasBorges-Santos

Reputation: 392

Django checkbox do not return nothing

I mading a project and i need to get checkbox values in sequence, but django do not return anything when that checkbox are unchecked. how can i do that return False instead of nothing?

forms.py

class myFormExemple(forms.Form):
    checkbox = forms.BooleanField(required=False)

views.py

def MyViewExemple(request):
    if request.method == 'POST':
        print(request.POST.getlist('checkbox'))
    context = {
        'form': myFormExemple
    }
    return render(request, "cadastro/myHTMLTemplate.html", context)

and myHTMLTemplate.html:

<form method="post" id='form'>
    {% csrf_token %}
    {{form.checkbox}}          
    <button type="submit">save</button>
</form>

Upvotes: 1

Views: 703

Answers (2)

thekiroo
thekiroo

Reputation: 1

I know it's an old post, but I stumbled upon a similar conundrum.

I ended up wrapping a CheckboxSelectMultiple widget with a single choice inside a MultipleChoiceField. This allows the form to still be valid even without a return. I think this is an important aspect as the form.is_valid() method should be used to actually validate the form and not as a try-except substitute.

This worked for my application

 pseudo_checkbox= forms.MultipleChoiceField(
    choices=[('checked', 'Check Me')],
    widget=forms.CheckboxSelectMultiple(),
)

And having

checkbox = bool(form.cleaned_data.get('pseudo_checkbox'))

In HTML, the multi checkboxes are treated as a list of checkboxes, so you can still change properties or apply functions to it.

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477240

If the checkbox is not checked, the POST request will indeed not contain the name of that checkbox, that is how the HTML form works.

You can however validate and clean the data with your form, and transform this into a boolean with:

def MyViewExemple(request):
    if request.method == 'POST':
        form = myFormExemple(request.POST)
        if form.is_valid():
            print(form.cleaned_data['checkbox'])
    context = {
        'form': myFormExemple()
    }
    return render(request, "cadastro/myHTMLTemplate.html", context)

We thus construct a form with request.POST as data source, and then if the form is valid, we can obtain a boolean with form.cleaned_data['checkbox'].

Django's forms are thus not only used to render a form, but also to process data of a form, validate that data, and convert the data to another type.

Upvotes: 2

Related Questions