|
1 | 1 | from dataclasses import dataclass, field as dataclass_field |
2 | 2 | from typing import Any, Dict, List, Optional, Set, Type, Union |
3 | 3 |
|
| 4 | +import django |
| 5 | +import rest_framework |
4 | 6 | from django import forms |
5 | 7 | from django.core.validators import ( |
6 | 8 | DecimalValidator, |
@@ -230,12 +232,18 @@ def add_unique_together_error_codes( |
230 | 232 | sfields_with_error_codes: "List[InputDataField]", |
231 | 233 | ) -> None: |
232 | 234 | for sfield in sfields_with_unique_together_validators: |
233 | | - sfield.error_codes.add("unique") |
234 | 235 | unique_together_validators = [ |
235 | 236 | validator |
236 | 237 | for validator in sfield.field.validators |
237 | 238 | if isinstance(validator, UniqueTogetherValidator) |
238 | 239 | ] |
| 240 | + if _drf_version() >= (3, 17) and django.VERSION >= (5, 0): |
| 241 | + # drf 3.17 passes the `custom_violation_error` added in django 5.0 |
| 242 | + # to `drf.UniqueTogetherValidator`. Before that, the error code was |
| 243 | + # hardcoded as `"unique"` |
| 244 | + sfield.error_codes.update(v.code for v in unique_together_validators) |
| 245 | + else: |
| 246 | + sfield.error_codes.add("unique") |
239 | 247 | # fields involved in a unique together constraint have an implied |
240 | 248 | # "required" state, so we're adding the "required" error code to them |
241 | 249 | implicitly_required_fields = set() |
@@ -501,3 +509,9 @@ def get_example_from_exception(exc: exceptions.APIException) -> OpenApiExample: |
501 | 509 | response_only=True, |
502 | 510 | status_codes=[str(exc.status_code)], |
503 | 511 | ) |
| 512 | + |
| 513 | + |
| 514 | +def _drf_version(): |
| 515 | + # we just care about major and minor drf versions |
| 516 | + parts = rest_framework.VERSION.split(".") |
| 517 | + return int(parts[0]), int(parts[1]) |
0 commit comments