2008-12-04 49 views
5

我想驗證提交的URL在數據庫中不存在。在Django表單上產生ValidationError的問題

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

Django的通道在這裏救了我。問題是,URLField.clean()做兩件事情我沒想到:

  1. 如果沒有URL方案存在(比如http://)的方法預規劃的「http://」的url
  2. 該方法還追加了一個尾部斜線。

結果被返回並存儲在窗體的cleaned_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

我這樣做。它稍微簡單一些。

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 
+0

沒有好 - 的錯誤不會引起人們的關注,當它應該。 – saturdayplace 2008-12-04 04:04:08

+0

那麼你還有其他問題。這必須工作。你運行的是「manage.py testserver」,每次運行時都會得到一個新的空數據庫?你正在運行「manage.py runserver」嗎? – 2008-12-04 11:11:50

0

我想,你可以返回''並填充_errors。在IRC

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