Python for Entrepreneurs Transcripts
Chapter: Build web apps with Pyramid: Applied web development
Lecture: Concept: Server-side validation with view models

Login or purchase this course to watch this video and the rest of the course contents.
0:02 We've seen how valuable view models can be for validation. Let's look at this a little more deeply.
0:08 Here we have what I would call a standard view model, we have a ViewModelBase, it has a "to dictionary",
0:13 we have the RegistrationViewModel, it has a __init__, it sets the fields, and it has a from_dict, so it will take in data as well as just return
0:22 whatever data you set to the view. If we are going to convert this to one that also supports validations, there is two simple steps we have to do;
0:30 first, we need to round trip some kind of error message so we are going to create a self.error, and in the beginning, everybody starts out pure,
0:38 there is no errors, there is nothing wrong here. However, we do want to have the ability to add some rules,
0:44 potentially set some errors, so we do that by adding a compute_errors function, now the way it works is we create one of these view models,
0:50 we say from_dict and then we call compute_errors and if something goes wrong, it's going to set the error message, then in our action,
0:58 we can check and see if there is an error, there is no error, everything was good, the validation passed, if there was, well maybe we want to stop.
1:04 we could also return some kind of boolean expression from here but since we are going to need the error message anyway
1:09 to do anything useful in the form, we might as well just use that.

Talk Python's Mastodon Michael Kennedy's Mastodon