django - 在 CreateView 表单中显示 django unique_together 的错误
问题描述
我正在使用 Django CBV CreateView 并在模型上有一个 unique_together 设置
class Meta:
unique_together = ('field1', 'field2',)
当用户添加一条非唯一的新记录时,会触发数据库级别的错误,即 500 错误。我只想向用户解释他们的条目是重复的并添加其他内容。
对于使用 CBV 和 unique_together 设置(或验证器)的简单方法有什么想法吗?我想将此保留在模型级别,以便无论用户是否创建、编辑或管理员是否在 Django 管理员中执行此操作,都会进行唯一检查。
谢谢!
解决方案
您可以在 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
推荐阅读
- javascript - 在 NodeJS 中正确声明常量以防止内存泄漏和正确缓存
- c - 为什么有符号的 char min -128 而不是 -127?
- r - R函数,多个If语句形式的长度和艺术
- python - 如何使用 boost/python 从 C++ 导入 .py 文件中的类?
- angular - Angular 材料中是否有 mat-toolbar-column?
- linux - 无法克隆 gitolite repo 并导致致命错误
- tensorflow - 使用 fit 恢复训练会将批处理步骤重置为 0
- kubernetes - 在开源 Kubernetes v1.14 上删除 cluster-admin ClusterRoleBinding 是否安全?
- python - Tkinter 可以在 macOS Catalina 上使用 Metal 吗?
- java - 在 Java 中将 ORC 转换为 JSON