[Django]-Boolean Field always saving False django

3👍

First, I recommend you to modify your serializer to check whether serializer recieves company_status. To make it change as the following:

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['id','username','user_image','designation','company_status','age','gender']
        extra_kwargs = dict(company_status=dict(required=True, allow_null=False))

    def create(self, validated_data):
        user = User.objects.create(**validated_data)
        return user

    def update(self, instance, validated_data):
        for k, v in validated_data.items():
            setattr(instance, k, v)
            instance.save()
        return instance

If serializer raises ValidationError, then most probably your serializer can not understand the request.data and thus, can not deserialize properly. Here you have to look at your React code whether it is sending with content-type:application/json in request header.

Second, if it is not the case, check your model migrations, maybe in the beginning you had boolean field with default=False and then you have made changes, but forgot to migrate the changes.

Third, even if it does not help, then maybe the problem is even deeper inside at the lowest level of your database configuration if you made some changes to your database settings before.

Even if it is not the case, then I am really sorry to tell you that you have messed up with your project settings.

0👍

If you use new FormData() to build your payload, then any boolean fields will be processed correctly by the serializer, but if you’re using a table and submitting a row when all data is present (POST) or submitting when a change is made (PUT), then you have no <form id="form_name"></form> tags surrounding the data that you want to submit and so can’t do new FormData(form_name) to create your payload. The following works to create the payload in this latter situation (note that checkbox values are set to on or off and are set in an opposite manner from which you would expect):

function submitRow($tr, deleteRow) {
    // Build data for submission but return if any item does not have data
    var data = {};
    ready = true;
    if (!deleteRow) {
        // Determine whether all data in a row is present
        $tr.find('input, select').each(function(idx, el){
            if ($(el).val() == '' && !($(el).attr('type') == 'checkbox')) {
                ready = false;
                return false;
            }
            // The state of the checkbox is still opposite at this point
            if ($(el).attr('type') == 'checkbox' && el.checked) {
                data[$(el).attr('name')] = 'on';
            } else if ($(el).attr('type') == 'checkbox' && !el.checked) {
                data[$(el).attr('name')] = 'off';
            } else {
                data[$(el).attr('name')] = $(el).val();
            }
        })
    }
    data['csrfmiddlewaretoken'] = $('input[name="csrfmiddlewaretoken"]').val();

    if (ready) {
        data = JSON.stringify(data);
        // Set up submission type
        if (deleteRow) {
            var method = 'DELETE'
            var url = '/child/delete/' + $tr.data('child-reg-id') + '/'
        }
        else if ($tr.data('child-reg-id') == '') {
            var method = 'POST'
            var url = '/child/add/'
        } else {
            var method = 'PUT'
            var url = '/child/update/' + $tr.data('child-reg-id') + '/'
        }
        
        fetch(url, {
            method: method,
            headers: {
                "X-CSRFToken": $('input[name="csrfmiddlewaretoken"]').first().val(),
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            credentials: 'include',
            body: data
        })
        .then(function(result) {
            return result.json();
        })
        .then(function(data) {
            // Final logic to process the returned data
        })
    }
}

Be sure to set up submission of the tr like this:

$('table tbody').on("change", "tr input, tr select", function(e) {
    submitRow($(e.target).closest('tr'), false);
})
// Handle deleting a row in which a Font Awesome "remove" icon is present in the row and is clicked to delete the row
$('table tbody').on("click", ".fa-remove", function(e) {
    submitRow($(e.target).closest('tr'), true);
})

Leave a comment