Django: How to save the POST.get of a checkbox as false (0) in a DataBase?
<p>I'm trying to save the value of a checkbox as true or false in a database. I have to use a model for this. If the box is checked the value of '1' is saved. However, if the box is not checked I get the error message: </p>

<pre><code>Django Version:     1.9.4
Exception Type:     IntegrityError
Exception Value:    (1048, "Column 'completed' cannot be null")
</code></pre>

<p>Currently my setup looks like this: </p>

<p>In models.py I have:</p>

<pre><code>class myClass(models.Model): 
    completed = models.BooleanField(default=False, blank=True)
</code></pre>

<p>In views.py I have:</p>

<pre><code>def create_myClass(request):
    completed = request.POST.get('completed')
    toSave = models.myClass(completed=completed)
    toSave.save()
</code></pre>

<p>and in the HTML I have:</p>

<pre><code>&lt;label class="col-md-5" for="completed"&gt; Completed: &lt;/label&gt;
&lt;input id="completed" type="checkbox" name="completed"&gt;
</code></pre>

<p><br></p>

<p>I've tried to set required = False in the BooleanField as some other posts suggested but then get the error: <code>TypeError: __init__() got an unexpected keyword argument 'required'</code>.</p>

<p>I've also tried to set 'completed' to False in views.py like:</p>

<pre><code>if request.POST.get('completed', False ):
    commpleted = False
</code></pre>

<p>and </p>

<pre><code>completed = request.POST.get('completed')
if completed == 'null':
    commpleted = False
</code></pre>

<p>But neither work (not sure if my syntax is correct?)</p>

<p>Any ideas or suggestions are greatly appreciated! </p>

<blockquote>
  <p>Use this code snippet</p>
</blockquote>

<pre><code>def create_myClass(request):
    completed = request.POST.get('completed')
    if not completed:
        completed = False
    toSave = models.myClass(completed=completed)
    toSave.save()
</code></pre>

python django django-models django-views