问题
I'm having this form with this validator for uniqueness:
class CreateTypeForm(FlaskForm):
type_name = StringField("Type", validators=[DataRequired()])
description = TextAreaField("Description")
submit = SubmitField("Create")
def validate_type_name(self, type_name):
typeName = mongo.db.types.find_one({"type_name": type_name.data})
if typeName:
raise ValidationError("The type already exists.")
But need to alter the validator for the form I have when I edit my type
:
class EditTypeForm(FlaskForm):
type_name = StringField("Type", validators=[DataRequired()])
description = TextAreaField("Description")
submit = SubmitField("Update")
So it checks for duplicates but allowing me to keep my current type_name
if I were to edit only the description and not the name.
What's the way to do this?
In short, how to check the duplication of the type name but also allow saving the original type name?
UPDATE:
Following the gentle advice from the answer below, I have now in my form:
class EditTypeForm(FlaskForm):
origin_type_name = HiddenField()
type_name = StringField("Type", validators=[DataRequired()])
description = TextAreaField("Description")
submit = SubmitField("Update")
def validate_type_name(self, type_name):
typeName = mongo.db.types.find_one({"type_name": type_name.data})
if typeName and type_name.data != self.origin_type_name.data:
raise ValidationError("The type already exists.")
And in the route:
@app.route("/type/edit/<id>", methods=["POST", "GET"])
@login_required
def edit_type(id):
form = EditTypeForm()
query = mongo.db.types.find_one(
{"_id": ObjectId(id)}, {"_id": 0, "type_name": 1}
)
current_type_name = query['type_name']
form.origin_type_name.data = current_type_name
(etc...)
This is now working perfectly!!
回答1:
Maybe there are better solutions, but I got this one:
- Store the origin type name in a hidden field, then check it in custom validator:
class EditTypeForm(FlaskForm):
origin_type_name = HiddenField() # import HiddenField first
type_name = StringField("Type", validators=[DataRequired()])
description = TextAreaField("Description")
submit = SubmitField("Create")
def validate_type_name(self, type_name):
typeName = mongo.db.types.find_one({"type_name": type_name.data})
if typeName and type_name.data != self.origin_type_name.data:
raise ValidationError("The type already exists.")
- Set the origin type name in view function before the template rendered:
form = EditTypeForm()
form.origin_type_name.data = the_origin_data_get_from_database
来源:https://stackoverflow.com/questions/61896450/check-duplication-when-edit-an-exist-database-field-with-wtforms-custom-validato