Gar*_*nzo 4 django django-validation
我的数据库中有客户记录列表。每年,我们都会为每个客户生成一个工作订单。然后,对于每个工单记录,用户应该能够创建特定于工单的注释。然而,并不是所有的工单都需要注释,只是一些。
现在,我不能简单地note向工作订单添加一个字段,因为有时,我们甚至需要在生成工作订单之前创建注释。有时,此注释特定于 2-3 年内不会发生的工作订单。因此,注释和工单必须是独立的,尽管当它们都存在时它们会“找到”彼此。
好的,情况就是这样。我希望用户能够填写一个非常简单的note表单,其中有两个字段:noteYear和note。因此,他们所做的就是选择一年,然后写下笔记。关键是用户不应该能够为同一个客户在同一年创建两个笔记。
我试图通过确保该客户没有该年的注释来验证该注释。我假设这将通过is_valid表单中的自定义方法来实现,但我不知道如何去做。
这是我到目前为止所尝试的(请注意,我知道这是错误的,它不起作用,但这是我迄今为止的尝试):
请注意,这systemID是我的客户记录
我的型号:
class su_note(models.Model):
YEAR_CHOICES = (
('2013', 2013),
('2014', 2014),
('2015', 2015),
('2016', 2016),
('2017', 2017),
('2018', 2018),
('2019', 2019),
('2020', 2020),
('2021', 2021),
('2022', 2022),
('2023', 2023),
)
noteYear = models.CharField(choices = YEAR_CHOICES, max_length = 4, verbose_name = 'Relevant Year')
systemID = models.ForeignKey(System, verbose_name = 'System ID')
note = models.TextField(verbose_name = "Note")
def __unicode__(self):
return u'%s | %s | %s' % (self.systemID.systemID, self.noteYear, self.noteType)
Run Code Online (Sandbox Code Playgroud)
还有我的表格:
class SU_Note_Form(ModelForm):
class Meta:
model = su_note
fields = ('noteYear', 'noteType', 'note')
def is_valid(self):
valid = super (SU_Note_Form, self).is_valid()
#If it is not valid, we're done -- send it back to the user to correct errors
if not valid:
return valid
# now to check that there is only one record of SU for the system
sysID = self.cleaned_data['systemID']
sysID = sysID.systemID
snotes = su_note.objects.filter(noteYear = self.cleaned_data['noteYear'])
for s in snotes:
if s.systemID == self.systemID:
self._errors['Validation_Error'] = 'There is already a startup note for this year'
return False
return True
Run Code Online (Sandbox Code Playgroud)
编辑- 这是我的解决方案(感谢 janos 向我发送正确的方向)
我的最终形式如下所示:
class SU_Note_Form(ModelForm):
class Meta:
model = su_note
fields = ('systemID', 'noteYear', 'noteType', 'note')
def clean(self):
cleaned_data = super(SU_Note_Form, self).clean()
sysID = cleaned_data['systemID']
sysID = sysID.systemID
try:
s = su_note.objects.get(noteYear = cleaned_data['noteYear'], systemID__systemID = sysID)
print(s)
self.errors['noteYear'] = "There is already a note for this year."
except:
pass
return cleaned_data
Run Code Online (Sandbox Code Playgroud)
对于查看此代码的其他任何人,唯一令人困惑的部分是具有以下内容的行:sysID = sysID.systemID. 这systemID实际上是另一个模型的一个领域——尽管systemID也是这个模型的一个领域——设计很差,可能,但它有效。
在 Django 文档中查看此页面:https : //docs.djangoproject.com/en/dev/ref/forms/validation/
由于您的验证逻辑取决于两个字段(年份和系统 ID),您需要使用表单上的自定义清理方法来实现这一点,例如:
def clean(self):
cleaned_data = super(SU_Note_Form, self).clean()
sysID = cleaned_data['systemID']
sysID = sysID.systemID
try:
su_note.objects.get(noteYear=cleaned_data['noteYear'], systemID=systemID)
raise forms.ValidationError('There is already a startup note for this year')
except su_note.DoesNotExist:
pass
# Always return the full collection of cleaned data.
return cleaned_data
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4786 次 |
| 最近记录: |