Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added URLField to django.newforms.fields

git-svn-id: http://code.djangoproject.com/svn/django/trunk@3955 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit c58fe999a1858308b677fb0b65b88b79028228d4 1 parent 7bff9cc
Adrian Holovaty adrianholovaty authored
Showing with 24 additions and 1 deletion.
  1. +24 −1 django/newforms/fields.py
25 django/newforms/fields.py
View
@@ -12,7 +12,7 @@
'Field', 'CharField', 'IntegerField',
'DEFAULT_DATE_INPUT_FORMATS', 'DateField',
'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.
@@ -175,6 +175,29 @@ class EmailField(RegexField):
def __init__(self, required=True, widget=None):
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):
widget = CheckboxInput
Please sign in to comment.
Something went wrong with that request. Please try again.