Created
March 18, 2025 16:19
-
-
Save tim-schilling/bb5dde79b4cb3f377bd1ed187805b23f to your computer and use it in GitHub Desktop.
Validate UniqueConstraint on a non-field for a Django ModelFOrm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyModelForm(ModelForm): | |
def validate_unique(self): | |
""" | |
Call the instance's validate_unique() method and update the form's | |
validation errors if any were raised. | |
""" | |
exclude = self._get_validation_exclusions() | |
# Don't exclude validation constraints on the basis of the Endpoint | |
# field. The value is set before .is_valid() is called, so we want | |
# to evaluate it. | |
exclude.remove("endpoint") | |
# Duplicate Model.validate_unique() so that we can | |
# evaluate unique constraints that are set in Meta.constraints | |
unique_checks, date_checks = self.instance._get_unique_checks( | |
exclude=exclude, | |
include_meta_constraints=True, | |
) | |
errors = self.instance._perform_unique_checks(unique_checks) | |
date_errors = self.instance._perform_date_checks(date_checks) | |
for k, v in date_errors.items(): | |
errors.setdefault(k, []).extend(v) | |
if errors: | |
# ModelForm.validate_unique catches the ValidationError from | |
# Model.validate_unique then calls _update_errors() | |
self._update_errors(errors) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment