需要阻止用户使用相同的数据创建记录:
in ** models.py **我添加了:
class Materiale(models.Model):
class Meta:
unique_together = (("data_rif","causale","rapp_rif", "articolo","qta", "nota"),)
这是我在** form.py **中添加的内容:
class CreaMaterialeForm(forms.ModelForm):
class Meta:
model = Materiale
fields = ('articolo','qta','udm')
error_messages = {
NON_FIELD_ERRORS: {
'unique_together': "%(model_name)s's %(field_labels)s are not unique.",
}
}
但每次提交重复数据时,我都会进入django错误屏幕:
django.db.utils.IntegrityError
IntegrityError:UNIQUE约束失败:mat_app_materiale.DATA_RIF, mat_app_materiale.CAUSALE,mat_app_materiale.rapp_rif_id, mat_app_materiale.ARTICOLO,mat_app_materiale.QTA, mat_app_materiale.NOTA
File ".virtualenvs/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py",
line 323, in execute
return Database.Cursor.execute(self, query, params)
IntegrityError: UNIQUE constraint failed: mat_app_materiale.DATA_RIF, mat_app_materiale.CAUSALE,
mat_app_materiale.rapp_rif_id, mat_app_materiale.ARTICOLO,
mat_app_materiale.QTA, mat_app_materiale.NOTA
如果它在这里意味着表单已经过验证并提交给db。所以缺少某些东西,是否有其他东西允许表单返回错误消息而不是访问django.db.utils.IntegrityError错误屏幕?
视图是:
class MaterialeCreate(CreateView):
form_class = CreaMaterialeForm
def form_valid(self, form):
form.instance.data_rif=form.cleaned_data['data_rif']
rapportino_rif = Rapporto.objects.get(pk=self.kwargs['rapp_rif'])
form.instance.rapp_rif=rapportino_rif