Django的ModelForm unique_together验证
我有一个看起来像这样的Django模型。
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用来手动检查此问题,但我想知道是否有任何方法可以在表单验证中捕获此问题并自动返回表单错误。
谢谢。
回答:
我通过重写validate_unique()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)
现在,我只是始终确保表单上未提供的属性仍然可用,例如instance=Solution(problem=some_problem)在初始化程序上。
以上是 Django的ModelForm unique_together验证 的全部内容, 来源链接: utcz.com/qa/420360.html

