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