Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

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 authored November 01, 2006

Showing 1 changed file with 24 additions and 1 deletion. Show diff stats Hide diff stats

  1. 25  django/newforms/fields.py
25  django/newforms/fields.py
@@ -12,7 +12,7 @@
12 12
     'Field', 'CharField', 'IntegerField',
13 13
     'DEFAULT_DATE_INPUT_FORMATS', 'DateField',
14 14
     'DEFAULT_DATETIME_INPUT_FORMATS', 'DateTimeField',
15  
-    'RegexField', 'EmailField', 'BooleanField',
  15
+    'RegexField', 'EmailField', 'URLField', 'BooleanField',
16 16
 )
17 17
 
18 18
 # These values, if given to to_python(), will trigger the self.required check.
@@ -175,6 +175,29 @@ class EmailField(RegexField):
175 175
     def __init__(self, required=True, widget=None):
176 176
         RegexField.__init__(self, email_re, u'Enter a valid e-mail address.', required, widget)
177 177
 
  178
+url_re = re.compile(
  179
+    r'^https?://' # http:// or https://
  180
+    r'(?:[A-Z0-9-]+\.)+[A-Z]{2,6}' # domain
  181
+    r'(?::\d+)?' # optional port
  182
+    r'(?:/?|/\S+)$', re.IGNORECASE)
  183
+
  184
+class URLField(RegexField):
  185
+    def __init__(self, required=True, verify_exists=False, widget=None):
  186
+        RegexField.__init__(self, url_re, u'Enter a valid URL.', required, widget)
  187
+        self.verify_exists = verify_exists
  188
+
  189
+    def to_python(self, value):
  190
+        value = RegexField.to_python(self, value)
  191
+        if self.verify_exists:
  192
+            import urllib2
  193
+            try:
  194
+                u = urllib2.urlopen(value)
  195
+            except ValueError:
  196
+                raise ValidationError(u'Enter a valid URL.')
  197
+            except: # urllib2.URLError, httplib.InvalidURL, etc.
  198
+                raise ValidationError(u'This URL appears to be a broken link.')
  199
+        return value
  200
+
178 201
 class BooleanField(Field):
179 202
     widget = CheckboxInput
180 203
 

0 notes on commit c58fe99

Please sign in to comment.
Something went wrong with that request. Please try again.