首页 > 解决方案 > 在 CreateView 表单中显示 django unique_together 的错误

问题描述

我正在使用 Django CBV CreateView 并在模型上有一个 unique_together 设置

class Meta:
    unique_together = ('field1', 'field2',)

当用户添加一条非唯一的新记录时,会触发数据库级别的错误,即 500 错误。我只想向用户解释他们的条目是重复的并添加其他内容。

对于使用 CBV 和 unique_together 设置(或验证器)的简单方法有什么想法吗?我想将此保留在模型级别,以便无论用户是否创建、编辑或管理员是否在 Django 管理员中执行此操作,都会进行唯一检查。

谢谢!

标签: djangodjango-models

解决方案


您可以在 ModelForm 中覆盖 clean 方法来验证 unique_togther

class AwesomeForm(forms.ModelForm):

    def clean(self):
        cleaned_data = self.cleaned_data
        if Model.objects.filter(field1=cleaned_data['field1'],         
                                   field2=cleaned_data['field1').exists():
            raise ValidationError(
                  'Solution with this Name already exists for this problem')

        return cleaned_data

推荐阅读