Skip to content

UUID validator fails if field.data is a UUID object instead of str #549

Open
@caumons

Description

@caumons

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions