Django's ModelForm unique_together validation
django, modelform, validation
Solution
I managed to fix this without modifying the view by adding a clean method to my form:
class SolutionForm(forms.ModelForm):
class Meta:
model = Solution
exclude = ['problem']
def clean(self):
cleaned_data = self.cleaned_data
try:
Solution.objects.get(name=cleaned_data['name'], problem=self.problem)
except Solution.DoesNotExist:
pass
else:
raise ValidationError('Solution with this Name already exists for this problem')
# Always return cleaned_data
return cleaned_data
The only thing I need to do now in the view is to add a problem property to the form before executing `is_valid`.
Problem
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.