我正在检查是否存在某个ID。我正在用干净的方法检查它。
当我键入"正确" (存在)号码,它告诉我'int' object is not subscriptable
当我输入错误(不存在)号码时,它会告诉我local variable 'result' referenced before assignment
原因是我无法检查ID(来自数据库)?
我的代码:
class IDForm(forms.Form):
ID = forms.IntegerField(required=True)
def clean(self):
id = self.cleaned_data['ID']
try:
result = pmod.RentalInventory.objects.get(id=id)
except result.DoesNotExist:
raise forms.ValidationError("Invalid Number")
return self.cleaned_data['ID']
我做了一些更改:现在当我键入正确的数字时,它会通过。当我输入错误的数字时,会显示RentalInventory matching query does not exist
。
def clean_email(self):
result = pmod.RentalInventory.objects.filter(email=self.cleaned_data['ID'])
if result.count() < 1:
raise forms.ValidationError("Invalid number")
return self.cleaned_data['ID']
答案 0 :(得分:3)
clean
方法应always返回已清理数据的完整集合。try
部分中没有数字对象,则result
未设置,因此您无法在exception
部分中使用它。所以将代码更改为:
from django.core.exceptions import ObjectDoesNotExist
class IDForm(forms.Form):
ID = forms.IntegerField(required=True)
def clean(self):
id = self.cleaned_data['ID']
try:
result = pmod.RentalInventory.objects.get(id=id)
except ObjectDoesNotExist:
raise forms.ValidationError("Invalid Number")
return self.cleaned_data