且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Django中保存表单数据之前进行重复检查

更新时间:2023-09-16 11:55:34

我认为您应该在 Course.name 字段上设置 unique = True 并让框架为您处理该验证.

I think you should just set unique=True on the Course.name field and let the framework handle that validation for you.

更新:

由于 unique = True 不是适合您的情况的正确答案,因此您可以通过以下方式进行检查:

Since unique=True is not the right answer for your case, you can check this way:

def clean(self):
    """ 
    Override the default clean method to check whether this course has
    been already inputted.
    """    
    cleaned_data = self.cleaned_data
    name = cleaned_data.get('name')

    matching_courses = Course.objects.filter(name=name)
    if self.instance:
        matching_courses = matching_courses.exclude(pk=self.instance.pk)
    if matching_courses.exists():
        msg = u"Course name: %s has already exist." % name
        raise ValidationError(msg)
    else:
        return self.cleaned_data

class Meta:
    model = Course

作为旁注,我还更改了自定义错误处理,以使用更标准的 ValidationError .

As a side note, I've also changed your custom error handling to use a more standard ValidationError.