在Django表单上引发ValidationError的问题

时间:2008-12-04 01:51:26

标签: python django django-forms cleaned-data

我正在尝试验证数据库中是否已存在提交的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也是如此。有什么想法吗?

4 个答案:

答案 0 :(得分:4)

IRC的django频道救了我。问题是URLField.clean()做了两件我没想到的事情:

  1. 如果不存在URL方案(例如,http://),则该方法将“http://”添加到网址
  2. 该方法还附加一个斜杠。
  3. 返回结果并存储在表单的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文档:

http://docs.djangoproject.com/en/1.2/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other