Django 的 ModelForm unique_together 验证 [英] Django's ModelForm unique_together validation

查看:31
本文介绍了Django 的 ModelForm unique_together 验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的 Django 模型.

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']

我的问题是 SolutionForm 不验证 Solutionunique_together 约束,因此,它返回一个 IntegrityError 尝试保存表单时.我知道我可以使用 validate_unique 来手动检查这个,但我想知道是否有任何方法可以在表单验证中捕获它并自动返回表单错误.

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.

谢谢.

推荐答案

我设法在不修改视图的情况下通过向我的表单添加了一个干净的方法来解决这个问题:

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

我现在在视图中唯一需要做的就是在执行 is_valid 之前向表单添加一个问题属性.

The only thing I need to do now in the view is to add a problem property to the form before executing is_valid.

这篇关于Django 的 ModelForm unique_together 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆