Search code examples
djangocheckboxdjango-forms

Django checkbox input only working in one direction


I have a form with a checkbox on "pregnant". If the profile is not pregnant and goes to the update profile form, checking the box and submitting the form updates the profile. I can see in the dashboard it appears as pregnant now.

However, if the profile is pregnant, and goes to update profile, unchecking the checkbox (prepopulated) and submitting, it does nothing! The profile information does not update (it still appears as pregnant in the dashboard).

I am puzzled because the form connects to the database (it can update from non-pregnant to pregnant) but not the other way around! What am I missing? :-/

See my code. view:

def edit_profile(request):
    if request.user.is_authenticated:
        current_user = Account.objects.get(id=request.user.id)
        form = EditProfileForm(request.POST or None, instance=current_user)
        if form.is_valid():
            form.save()
            messages.success(request,("Your profile has been updated!"))
            return redirect('dashboard')
        return render(request, 'accounts/edit_profile.html',context={'form':form}) #
    else:
        messages.success(request,('You must be logged in!'))
        return redirect('login')

html:

                            <div class="flex col col-auto form-group form-check">
                                <label><input type="checkbox" id="pregnancy" value="Yes" name="pregnancy" {% if form.instance.pregnancy == 'Yes' %} checked {% endif %}> {% trans " Pregnant" %}</label>
                            </div>

model:

class Account(AbstractBaseUser):
    ....
    pregnancy = models.CharField(max_length=10,blank=True, null=True, default='No')

Solution

  • It seems the "problem" is related to HTML, so I need to add "negative" input hidden before the checkbox. This is like an underlying default case whenever there is no input. So the solution is:

    <div class="flex col col-auto form-group form-check">
        <input type="hidden" name="pregnancy" value="No" />
        <label><input type="checkbox" id="pregnancy" value="Yes" name="pregnancy" {% if form.instance.pregnancy == 'Yes' %} checked {% endif %}> {% trans " Pregnant" %}</label>
    </div>