Django's ModelForm unique_together validation

sttwister picture sttwister · Jan 26, 2010 · Viewed 20.9k times · Source

I have a Django model that looks like this.

class Solution(models.Model):
    '''
    Represents a solution to a specific problem.
    '''
    name = models.CharField(max_length=50)
    problem = models.ForeignKey(Problem)
    description = models.TextField(blank=True)
    date = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ("name", "problem")

I use a form for adding models that looks like this:

class SolutionForm(forms.ModelForm):
    class Meta:
        model = Solution
        exclude = ['problem']

My problem is that the SolutionForm does not validate Solution's unique_together constraint and thus, it returns an IntegrityError when trying to save the form. I know that I could use validate_unique to manually check for this but I was wondering if there's any way to catch this in the form validation and return a form error automatically.

Thanks.

Answer

Jarmo Jaakkola picture Jarmo Jaakkola · Sep 21, 2010

I solved this same problem by overriding the validate_unique() method of the ModelForm:


def validate_unique(self):
    exclude = self._get_validation_exclusions()
    exclude.remove('problem') # allow checking against the missing attribute

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

Now I just always make sure that the attribute not provided on the form is still available, e.g. instance=Solution(problem=some_problem) on the initializer.