[Answered ]-ModelForm and unique_together validation

2👍

unique_together is a database-level constraint. It’s supposed to be specified in the Meta class of the model, not the model form. For the validation to work as you would like, move it to the Wiki model. In your form, you probably won’t even need to have those extra validation methods.

This doesn’t look like it’d be the case for you, but also note that in order for the unique validation to work correctly, your model form must include all of the fields that are specified in the unique_together constraint. So, if related_model or related_id were excluded from the form, you’d need to do some extra work in order to allow the correct validation to happen:

def validate_unique(self):
    # Must remove organization field from exclude in order
    # for the unique_together constraint to be enforced.
    exclude = self._get_validation_exclusions()
    exclude.remove('organization')

    try:
        self.instance.validate_unique(exclude=exclude)
    except ValidationError, e:
        self._update_errors(e.message_dict)

In the example above I am removing organization from the form’s list of excluded fields because it’s part of the unique_together constraint.

Leave a comment