我有一个姜戈模型看起来像这样。
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")
我使用一个表单来添加如下模型:
class SolutionForm(forms.ModelForm):
class Meta:
model = Solution
exclude = ['problem']
我的问题是,SolutionForm
不验证 Solution
的 unique_together
约束,因此,它在尝试保存表单时返回一个 IntegrityError
。我知道我可以使用 validate_unique
手动检查这一点,但我想知道是否有任何方法可以在表单验证中捕捉到这一点,并自动返回表单错误。
谢谢。