Data is missing after using @validate with Schema

132 views Asked by At

I'm working on validating my webapp, which is using Turbogears 2.3.3 and formencode 1.3

I want to validate a dynamic form that the user has created through a form creation process. I'm sending the form fields from the client to the server using json to help organize things.
Here is how I'm sending the data:

var dataToSend = JSON.stringify({
        'num_of_copies': num_of_copies.val(),
        'amountAnswers' : amountAnswers,
        'yesNoAnswers' : yesNoAnswers,
        'selectAnswers' : selectAnswers,
        'comments':comments.val()
    })

    $.ajax({
        type: 'POST',
        url: siteProxy+'orders/saveOrderItem',
        data: {'data':dataToSend},
        dataType: "json",
        success: function (data, textStatus) {
            if (textStatus == "success") {
                if (data.errors){
                    console.log(data.errors)
                }
            }
        },
        error: function (data, textStatus) {
            alert('error');
        }
    })

On The server I want to validate the data and then do some stuff

@expose('json')
@validate(validators=orderItemSchema(),error_handler=simpleErrorHandler)
def saveOrderItem(self,**kw):
    answers = json.loads(kw['data'])
    ...... do stuff ...

Without the validations, my code works.

Here is my validation Schema:

class orderItemSchema(Schema):
    def _convert_to_python(self, value_dict, state):
        value_dict = json.loads(value_dict['data'])
        super(orderItemSchema,self)._convert_to_python(value_dict, state)

    num_of_copies = validators.Number(min=1)
    comments = validators.UnicodeString()
    amountAnswers = ForEach(AmountAnswerValidator())
    yesNoAnswers = ForEach(YesNoAnswerValidator())
    selectAnswers = ForEach(SelectAnswerValidator())

The validation works well.


My problem is this: after the validation, kw turns to none, and I can't do stuff in

def saveOrderItem(self,**kw):

I think the problem lies somewhere in this part of the code:

class orderItemSchema(Schema):
    def _convert_to_python(self, value_dict, state):
        value_dict = json.loads(value_dict['data'])
        super(orderItemSchema,self)._convert_to_python(value_dict, state)

Thanks for the help

1

There are 1 answers

1
amol On BEST ANSWER

Probably orderItemSchema._convert_to_python is missing return value. Should be return super(orderItemSchema,self)._convert_to_python(value_dict, state) or you will be returning None as the converted value.

If you are using a recent tg version I suggest you also have a look at @decode_params decorator ( http://turbogears.readthedocs.org/en/latest/reference/classes.html#tg.decorators.decode_params ), it will extract the controller parameters from the json body and let validation flow as usual. It will avoid the two json.load in your code.