| 1 |
from django.core.exceptions import ValidationError |
| 2 |
from django.utils.functional import SimpleLazyObject |
| 3 |
from django.utils.text import format_lazy |
| 4 |
|
| 5 |
|
| 6 |
def prefix_validation_error(error, prefix, code, params): |
| 7 |
""" |
| 8 |
Prefix a validation error message while maintaining the existing |
| 9 |
validation data structure. |
| 10 |
""" |
| 11 |
if error.error_list == [error]: |
| 12 |
error_params = error.params or {} |
| 13 |
return ValidationError( |
| 14 |
# We can't simply concatenate messages since they might require |
| 15 |
# their associated parameters to be expressed correctly which |
| 16 |
# is not something `format_lazy` does. For example, proxied |
| 17 |
# ngettext calls require a count parameter and are converted |
| 18 |
# to an empty string if they are missing it. |
| 19 |
message=format_lazy( |
| 20 |
"{} {}", |
| 21 |
SimpleLazyObject(lambda: prefix % params), |
| 22 |
SimpleLazyObject(lambda: error.message % error_params), |
| 23 |
), |
| 24 |
code=code, |
| 25 |
params={**error_params, **params}, |
| 26 |
) |
| 27 |
return ValidationError( |
| 28 |
[prefix_validation_error(e, prefix, code, params) for e in error.error_list] |
| 29 |
) |