Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango form with BooleanField always invalid unless checked
    primarykey
    data
    text
    <p>I have an application that uses the following form:</p> <pre><code>class ConfirmForm(forms.Form): account_name = forms.CharField(widget=forms.HiddenInput) up_to_date = forms.BooleanField(initial=True) </code></pre> <p>I use the form in the following template exerpt:</p> <pre><code>&lt;form class="confirmform" action="/foo/" enctype="multipart/form-data" method="post"&gt; {{ confirm_form.up_to_date }} Check if this data brings the account up to date.&lt;br&gt; {{ confirm_form.account_name }} &lt;input type="submit" name="confirm" value="Confirm" /&gt; &lt;/form&gt; </code></pre> <p>My view uses the following basic code structure:</p> <pre><code>if request.method == 'POST': #check for 'confirm' because I actually have multiple forms in this page if 'confirm' in request.POST: confirm_form = ConfirmForm(request.POST) if confirm_form.is_valid(): #do stuff else: c['confirm_form'] = confirm_form else: c['confirm_form'] = ConfirmForm({'account_name':'provided_value'}) </code></pre> <p>Two things are wrong:</p> <p>1) Even though I have initial=True, the checkbox is unchecked when the page loads</p> <p>2) The form is always invalid unless I check the checkbox. It gives errors for up_to_date only: "This field is required."</p> <p>I have read <a href="https://stackoverflow.com/questions/1554142/django-form-with-just-a-booleanfield">this similar question</a> but his solution doesn't apply to my project.</p> <p>So... what's going on?</p> <p><strong>Edit:</strong></p> <p>I updated the code above to be more faithful to my actual code.</p> <p>Problem #1 was my fault because I was overriding the initial value by binding data when the form was instantiated.</p> <p>Problem #2 I still consider an issue. Using <code>required=False</code> on <code>up_to_date</code> will fix the problem, however it doesn't seem correct that using the default widget, a <code>BooleanField</code> can be either <code>NULL</code> (causes validity check to fail) or <code>True</code> but never <code>False</code>.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload