所以我有一个自定义表单字段,它基本上检查我的数据库以查看给定值(凭证代码)是否有效。我有 forms.py
class VoucherField(CharField):
def to_python(self, value):
if not value:
return ""
return value
def validate(self, value):
super(CharField, self).validate(value)
vouchers = Vouchers.objects[0]
if not value in vouchers.valid:
raise ValidationError('This voucher is invalid or has been used already.')
class PurchaseForm(Form):
voucher = VoucherField(required=True)
...
和views.py
def orderHandler(request):
form = PurchaseForm(request.POST)
if form.is_valid():
# Processes
else:
# Return errors
问题是form.is_valid()行不断导致Django抛出 ValidationError 而不是捕获它并将消息保存到form.errors。我不确定为什么会发生这种情况