Description
The current implementation of UUID
validator at https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py#L520 assumes that field.data is of type str
. However, if field.data
is already an instance of uuid.UUID
the validator fails with the following exception: AttributeError: 'UUID' object has no attribute 'replace'
.
I've found this issue working with PostgreSQL, SQLAlchemy and using Flask-Admin with a field declared as:
from sqlalchemy.dialects.postgresql import UUID
import sqlalchemy as sa
# ... More code here
uuid = db.Column(
UUID(as_uuid=True), nullable=False, default=uuid4,
server_default=sa.text('uuid_generate_v4()'), index=True)
Note the use of as_uuid=True
as said at pallets-eco/flask-admin#1444.
My proposal is to change this line uuid.UUID(field.data)
by uuid.UUID(str(field.data))
, this way it should work in both cases.
Meanwhile, I've done the following workaround implementing a new UUID validator overriding the __call__()
method as follows:
import uuid
from wtforms.validators import UUID
class SecureUUID(UUID):
def __call__(self, form, field):
if isinstance(field.data, uuid.UUID):
field.data = str(field.data)
super().__call__(form, field)