Skip to content

Commit

Permalink
Added URLField to django.newforms.fields
Browse files Browse the repository at this point in the history
git-svn-id: http://code.djangoproject.com/svn/django/trunk@3955 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information
adrianholovaty committed Nov 1, 2006
1 parent 7bff9cc commit c58fe99
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion django/newforms/fields.py
Expand Up @@ -12,7 +12,7 @@
'Field', 'CharField', 'IntegerField', 'Field', 'CharField', 'IntegerField',
'DEFAULT_DATE_INPUT_FORMATS', 'DateField', 'DEFAULT_DATE_INPUT_FORMATS', 'DateField',
'DEFAULT_DATETIME_INPUT_FORMATS', 'DateTimeField', 'DEFAULT_DATETIME_INPUT_FORMATS', 'DateTimeField',
'RegexField', 'EmailField', 'BooleanField', 'RegexField', 'EmailField', 'URLField', 'BooleanField',
) )


# These values, if given to to_python(), will trigger the self.required check. # These values, if given to to_python(), will trigger the self.required check.
Expand Down Expand Up @@ -175,6 +175,29 @@ class EmailField(RegexField):
def __init__(self, required=True, widget=None): def __init__(self, required=True, widget=None):
RegexField.__init__(self, email_re, u'Enter a valid e-mail address.', required, widget) RegexField.__init__(self, email_re, u'Enter a valid e-mail address.', required, widget)


url_re = re.compile(
r'^https?://' # http:// or https://
r'(?:[A-Z0-9-]+\.)+[A-Z]{2,6}' # domain
r'(?::\d+)?' # optional port
r'(?:/?|/\S+)$', re.IGNORECASE)

class URLField(RegexField):
def __init__(self, required=True, verify_exists=False, widget=None):
RegexField.__init__(self, url_re, u'Enter a valid URL.', required, widget)
self.verify_exists = verify_exists

def to_python(self, value):
value = RegexField.to_python(self, value)
if self.verify_exists:
import urllib2
try:
u = urllib2.urlopen(value)
except ValueError:
raise ValidationError(u'Enter a valid URL.')
except: # urllib2.URLError, httplib.InvalidURL, etc.
raise ValidationError(u'This URL appears to be a broken link.')
return value

class BooleanField(Field): class BooleanField(Field):
widget = CheckboxInput widget = CheckboxInput


Expand Down

0 comments on commit c58fe99

Please sign in to comment.