我正在尝试验证数据库中是否已存在提交的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也是如此。有什么想法吗?
答案 0 :(得分:4)
返回结果并存储在表单的cleaning_data中。所以我正在检查cleaned_data['url']
期待类似example.com
的内容并实际获得http://example.com/
。可以说,将我的clean_url()
方法更改为以下作品:
def clean_url(self):
url = self.cleaned_data['url']
bits = urlparse(url)
dom = bits[1]
try:
site=Site.objects.get(domain__iexact=dom)
except Site.DoesNotExist:
return dom
raise forms.ValidationError(u'That domain is already taken. Please choose another')
答案 1 :(得分:1)
try:
a = Site.objects.get(domain=url)
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
except Site.DoesNotExist:
pass
return url
答案 2 :(得分:0)
我认为,您可以返回''并填写_errors。
msg = u"That URL is already in the database. Please submit a unique URL."
self._errors["url"]=ErrorList([msg])
return ''
或
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)
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
except Site.DoesNotExist:
return url
return ''
def clean(self):
# Other form cleaning stuff. I don't *think* this is causing the grief
答案 3 :(得分:0)
我登录的原因是因为我在Google上发现了类似的问题并希望在Carl Meyers帖子中添加评论,并指出使用self._errors完全有效,因为Django文档: