Issues with raising ValidationError in Django form

I am trying to verify that the submitted URL does not yet exist in the database.

The relevant parts of the Form class are as follows:

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

The problem is that no matter what value I give, I can’t raise it ValidationError. And if I do something like this in a method clean_url():

if Site.objects.get(domain=url):
    raise forms.ValidationError("That URL is already in the database.  Please submit a unique URL.")

then I get an error DoesNotExist, even for URLs that already exist in the database. Any ideas?

+5
source share
4 answers

django's IRC channel saved me here. The problem was that URLField.clean () does two things that I did not expect:

  • URL- (, http://), "http://" URL-
  • .

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')
+4

. .

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

, '' _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
0

All Articles