我正在尝试验证数据库中不存在提交的 URL。
Form 类的相关部分如下所示:
from django.contrib.sites.models import Site
class SignUpForm(forms.Form):
# ... Other fields ...
url = forms.URLField(label='URL for new site, eg: example.com')
def clean_url(self):
url = self.cleaned_data['url']
try:
a = Site.objects.get(domain=url)
except Site.DoesNotExist:
return url
else:
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
def clean(self):
# Other form cleaning stuff. I don't *think* this is causing the grief
问题是,无论我提交什么值,我都无法提高ValidationError
. 如果我在方法中做这样的事情clean_url()
:
if Site.objects.get(domain=url):
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
然后我得到一个DoesNotExist
错误,即使是数据库中已经存在的 URL。有任何想法吗?