Python for Entrepreneurs Transcripts
Chapter: Build web apps with Pyramid: Applied web development
Lecture: Concept: Server-side validation with view models
0:02 We've seen how valuable view models can be for validation.
0:05 Let's look at this a little more deeply.
0:07 Here we have what I would call a standard view model,
0:10 we have a ViewModelBase, it has a "to dictionary",
0:12 we have the RegistrationViewModel, it has a __init__, it sets the fields,
0:15 and it has a from_dict, so it will take in data as well as just return
0:21 whatever data you set to the view.
0:24 If we are going to convert this to one that also supports validations,
0:26 there is two simple steps we have to do;
0:29 first, we need to round trip some kind of error message
0:33 so we are going to create a self.error,
0:35 and in the beginning, everybody starts out pure,
0:37 there is no errors, there is nothing wrong here.
0:39 However, we do want to have the ability to add some rules,
0:43 potentially set some errors, so we do that by adding a compute_errors function,
0:47 now the way it works is we create one of these view models,
0:49 we say from_dict and then we call compute_errors and if something goes wrong,
0:53 it's going to set the error message, then in our action,
0:57 we can check and see if there is an error, there is no error,
0:59 everything was good, the validation passed,
1:01 if there was, well maybe we want to stop.
1:03 we could also return some kind of boolean expression from here
1:05 but since we are going to need the error message anyway
1:08 to do anything useful in the form, we might as well just use that.