我确定这是一个简单的问题,但谷歌今天没有帮助我! 我试图仅在Create视图阶段运行以下验证,因为在某些时候系统需要允许重复,但不是在用户创建新计算时。
def clean_tag_number(self):
tag_number = self.cleaned_data['tag_number']
try:
Calc.objects.get(tag_number = tag_number)
except Calc.DoesNotExist:
return tag_number
raise forms.ValidationError("You already have a calculation based on that tag number, please choose another.")
我已尝试在request.path
中使用forms.py
检查当前网址,就像我在某些模板中所做的那样,但这显然不适用于forms.py
。任何指针都会非常感激。
答案 0 :(得分:1)
您可以使用现有方法,但请先检查self.instance
和self.instance.pk
是否为无。
答案 1 :(得分:0)
def clean_tag_number(self):
tag_number = self.cleaned_data['tag_number']
qs = self.Meta.model.objects.filter(tag_number=tag_number)
if self.instance:
qs = qs.exclude(pk=self.instance.id)
if qs.count() > 0:
raise forms.ValidationError('You already have a calculation based on that tag number, please choose another.')
return tag_number
答案 2 :(得分:0)
感谢帖子并详细说明Daniels的答案,我有以下工作代码。
def clean_tag_number(self):
tag_number = self.cleaned_data['tag_number']
if self.instance and self.instance.pk == None:
try:
Calc.objects.get(tag_number = tag_number)
except Calc.DoesNotExist:
return tag_number
except Calc.MultipleObjectsReturned:
raise forms.ValidationError("You already have a calculation based on that tag number, please choose another.")
raise forms.ValidationError("You already have a calculation based on that tag number, please choose another.")
else:
return tag_number
这是我第一次写任何验证,所以请随时指出任何问题。