I want the po_count and cpe_count fields only when the license_type is Production. The record is not going in the database which is what I want but it is not throwing messages when the user does not give values when the type is Production
class LicenseRequestForm(FlaskForm): salesperson = StringField('Salesperson Name', validators=[DataRequired()]) license_type_choices = [('Lab', 'Lab'), ('Production', 'Production')] license_type = SelectField('License Type', choices=license_type_choices, validators=[DataRequired()]) po_count = IntegerField('PO Count', validators=[Optional()]) cpe_count = IntegerField('Number of CPEs', validators=[Optional()])
ha = BooleanField('High Availability (HA) Option')
file1 = FileField('NodeID File 1', validators=[DataRequired()])
file2 = FileField('NodeID File 2', validators=[Optional()])
submit = SubmitField('Submit')
def validate(self, extra_validators=None):
if self.license_type.data == 'Production':
self.po_count.validators = [DataRequired()]
self.cpe_count.validators = [DataRequired()]
elif self.license_type.data == 'Lab':
self.po_count.validators = [Optional()]
self.cpe_count.validators = [Optional()]
if self.ha.data:
self.file1.validators = [DataRequired()]
self.file2.validators = [DataRequired()]
else:
self.file2.validators = [Optional()]
return super().validate()
I tried the validate method but still it did not show any message.
Maybe I'm getting something wrong, but let me get this forward
The user set license_type to PRO and is not giving values for po & cpe count and because this information is not enough, you'd like to give some kind of message like: 'Please set po, cpe count values'
If that's the case, flask offers flash, which is a message that it will be displayed if the user bad use the form, is really straight forward.
docs: https://flask.palletsprojects.com/en/2.3.x/patterns/flashing/
video explaining: https://www.youtube.com/watch?v=UIJKdCIEXUQ starting at timestamp 25:10
If this doesn't reply completely to your question, I'm pretty sure that you'll get your answer in the video attached above, also regarding data validation.
Kind regards!