how to raise validation Error after form.validate_on_Submit in flask route function

Viewed 22

sqlalchamy database throws an error of (IntegrityError UNIQUE) to handle it i am using try and except, but the problem is i can't figure out how to raise validation error on a form field which is raising this sql error. Dont want to use the validation inside the FLASKFROM Class because i am using one form on both creating and updating data.

i tried appending the error Message in form.errors but then i get attribute error of (form.errors does not have append attribute)

also the same question is asked before but solution provided here (wtforms raise a validation error after the form is validated) is done inside the FLASKFROM not in the route funciton.

My Question is the same as mentioned in the above link. Please help

@views.route("/Employees", methods=["GET", "POST"])
  form = AddNewEmployee()
  databaseModel = Employee()  #Database Model(db.Model)
  if submitBtn.data and form.validate_on_submit():
    if submitBtn.label.text == "Add Data":
      try:
        addEmploy = EmployeeBlock(databaseModel, form).addEmployee("newEmployee")
        db.session.add(addEmploy)
        db.session.commit()
      except IntegrityError:
        db.session.rollback()

        ****i want to raise ValidationError here and display it on to related field****
        
      else:
        *** Further code goes here ****
  else:
    if form.errors:
      print(form.errors)
 return render_template("employees.html", form=form)

i can the validate function shown below in the NumberFieldCheck Form Class but this also trigger when updating the data which would not let me update the data and throw an error of (Already Exist).

Also wont let me create new data if there is no duplicate entry in the database when this function is active, form.validate_on_Submit() comes back with False, even there is no errors because i think the field in the database is flagged with UNIQUE thats is why it might not letting me create new data.

class NumberFieldCheck(Form):
  regExp = r"^\d{4}$"
  msg = "Please enter only 4 numbers NO Alphabets"
  num1 = StringField("", render_kw={"placeholder": "0000"}, validators= 
            [Regexp(regex=regExp, message=msg), Length(min=4, max=4), DataRequired()])
  num2 = StringField("", render_kw={"placeholder": "0000"}, validators= 
            [Regexp(regex=regExp, message=msg), Length(min=4, max=4), DataRequired()])
  num3 = StringField("", render_kw={"placeholder": "0000"}, validators= 
            [Regexp(regex=regExp, message=msg), Length(min=4, max=4), DataRequired()])

  # def validate(self, extra_validators=None):
  #     if super().validate(extra_validators):
  #         NumberCheck = Employee.query.with_entities(Employee.aadharNum).all()
  #         if not len(NumberCheck) == 0:
  #             for num in NumberCheck:
  #                 if tuple(num)[0] == str(self.num1.data + "-" + self.num2.data 
                                           + "-" + self.num3.data):
  #                     self.num1.errors.append("Entered Number Already Exist")
  #                     self.num2.errors.append("Entered Number Already Exist")
  #                     self.num3.errors.append("Entered Number Already Exist")
  #                     return False
  #         else:
  #             return True

still by putting UNIQUE flag on the column in database work for the updating but not good for creating new data entries, because it is going to through an IntegrityError. So i want to raise a validation error in the routes function after the form is submitted.

Don't want to use flash for this.

Please if there is way to raise a validation errror and display it on form fields error will be great without using jQuery or javaScript

0 Answers
Related