I have a FlaskForm class where I'm validating whether a field value is already in the system and raise a ValidationError if required.
def validate_username(self, username_field):
if User.query.filter_by(username=username_field.data).first():
raise ValidationError("This username is already taken.")
For User, I ended up actually having to do a separate Form class with different validation to enable updating the model.
def validate_username(self, username_field):
if current_user.username != username_field.data:
if User.query.filter_by(username=username_field.data).first():
raise ValidationError("Cannot change username to this as it already is taken.")
But now I need to do it with another model that I can't access from the Form class as it is not tied to the user (it is dependent on the record being edited). I'm not sure how to go about doing this validation and would prefer not to have two FlaskForm classes for these models if possible.
Is there any way to apply certain validation methods to only a certain action (create vs. update) or do I have to write multiple FlaskForm classes for every model that has a field that is required to be unique?
I figured this design pattern must come up frequently but can't find a good example of handling it.
validate_on_submit()succeds?). - Dan