我使用Django的内置类定义了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对象定义中的消息。我该怎么办?
答案 0 :(得分:1)
捕获异常并使用验证错误的message
属性。
from django.core.exceptions import ValidationError
try:
validate_alphanumeric("++")
except ValidationError as exc:
message = exc.message