从 Django RegexValidator 对象中定义的获取消息

Getting the message from defined in a Django RegexValidator object

我使用 Django 的内置 class 定义了一个 RegexValidator。喜欢如下:

from django.core.validators import RegexValidator

validate_alphanumeric = RegexValidator(r'^[a-zA-Z0-9]*$', 'Only alphanumeric characters are allowed.')

问题是我在模型定义之外使用它。喜欢如下:

try:
    validate_alphanumeric("++")
except:
    # Somehow get the message defined above, that is get 'Only alphanumeric characters are allowed.'

换句话说,如果传递的字符串导致错误,我想获取存储在我的 RegexValidator 对象定义中的消息。我该怎么做?

捕获异常并使用验证错误的message属性。

from django.core.exceptions import ValidationError

try:
    validate_alphanumeric("++")
except ValidationError as exc:
    message = exc.message