mirror of
https://github.com/django/django.git
synced 2025-06-16 00:49:12 +00:00
magic-removal: Changed django.core.validators to use gettext() instead of magic _() function, to fix weird bug in unit tests
git-svn-id: http://code.djangoproject.com/svn/django/branches/magic-removal@1747 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
parent
5d630bcc60
commit
5eddd9612d
@ -8,6 +8,9 @@ validator will *always* be run, regardless of whether its associated
|
|||||||
form field is required.
|
form field is required.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
from django.conf.settings import JING_PATH
|
||||||
|
from django.utils.translation import gettext, gettext_lazy, ngettext
|
||||||
|
from django.utils.functional import Promise, lazy
|
||||||
import re
|
import re
|
||||||
|
|
||||||
_datere = r'\d{4}-((?:0?[1-9])|(?:1[0-2]))-((?:0?[1-9])|(?:[12][0-9])|(?:3[0-1]))'
|
_datere = r'\d{4}-((?:0?[1-9])|(?:1[0-2]))-((?:0?[1-9])|(?:[12][0-9])|(?:3[0-1]))'
|
||||||
@ -25,10 +28,6 @@ phone_re = re.compile(r'^[A-PR-Y0-9]{3}-[A-PR-Y0-9]{3}-[A-PR-Y0-9]{4}$', re.IGNO
|
|||||||
slug_re = re.compile(r'^[-\w]+$')
|
slug_re = re.compile(r'^[-\w]+$')
|
||||||
url_re = re.compile(r'^http://\S+$')
|
url_re = re.compile(r'^http://\S+$')
|
||||||
|
|
||||||
from django.conf.settings import JING_PATH
|
|
||||||
from django.utils.translation import gettext_lazy, ngettext
|
|
||||||
from django.utils.functional import Promise, lazy
|
|
||||||
|
|
||||||
lazy_inter = lazy(lambda a,b: str(a) % b, str)
|
lazy_inter = lazy(lambda a,b: str(a) % b, str)
|
||||||
|
|
||||||
class ValidationError(Exception):
|
class ValidationError(Exception):
|
||||||
@ -59,11 +58,11 @@ class CriticalValidationError(Exception):
|
|||||||
|
|
||||||
def isAlphaNumeric(field_data, all_data):
|
def isAlphaNumeric(field_data, all_data):
|
||||||
if not alnum_re.search(field_data):
|
if not alnum_re.search(field_data):
|
||||||
raise ValidationError, _("This value must contain only letters, numbers and underscores.")
|
raise ValidationError, gettext("This value must contain only letters, numbers and underscores.")
|
||||||
|
|
||||||
def isAlphaNumericURL(field_data, all_data):
|
def isAlphaNumericURL(field_data, all_data):
|
||||||
if not alnumurl_re.search(field_data):
|
if not alnumurl_re.search(field_data):
|
||||||
raise ValidationError, _("This value must contain only letters, numbers, underscores and slashes.")
|
raise ValidationError, gettext("This value must contain only letters, numbers, underscores and slashes.")
|
||||||
|
|
||||||
def isSlug(field_data, all_data):
|
def isSlug(field_data, all_data):
|
||||||
if not slug_re.search(field_data):
|
if not slug_re.search(field_data):
|
||||||
@ -71,18 +70,18 @@ def isSlug(field_data, all_data):
|
|||||||
|
|
||||||
def isLowerCase(field_data, all_data):
|
def isLowerCase(field_data, all_data):
|
||||||
if field_data.lower() != field_data:
|
if field_data.lower() != field_data:
|
||||||
raise ValidationError, _("Uppercase letters are not allowed here.")
|
raise ValidationError, gettext("Uppercase letters are not allowed here.")
|
||||||
|
|
||||||
def isUpperCase(field_data, all_data):
|
def isUpperCase(field_data, all_data):
|
||||||
if field_data.upper() != field_data:
|
if field_data.upper() != field_data:
|
||||||
raise ValidationError, _("Lowercase letters are not allowed here.")
|
raise ValidationError, gettext("Lowercase letters are not allowed here.")
|
||||||
|
|
||||||
def isCommaSeparatedIntegerList(field_data, all_data):
|
def isCommaSeparatedIntegerList(field_data, all_data):
|
||||||
for supposed_int in field_data.split(','):
|
for supposed_int in field_data.split(','):
|
||||||
try:
|
try:
|
||||||
int(supposed_int)
|
int(supposed_int)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
raise ValidationError, _("Enter only digits separated by commas.")
|
raise ValidationError, gettext("Enter only digits separated by commas.")
|
||||||
|
|
||||||
def isCommaSeparatedEmailList(field_data, all_data):
|
def isCommaSeparatedEmailList(field_data, all_data):
|
||||||
"""
|
"""
|
||||||
@ -94,48 +93,48 @@ def isCommaSeparatedEmailList(field_data, all_data):
|
|||||||
try:
|
try:
|
||||||
isValidEmail(supposed_email.strip(), '')
|
isValidEmail(supposed_email.strip(), '')
|
||||||
except ValidationError:
|
except ValidationError:
|
||||||
raise ValidationError, _("Enter valid e-mail addresses separated by commas.")
|
raise ValidationError, gettext("Enter valid e-mail addresses separated by commas.")
|
||||||
|
|
||||||
def isValidIPAddress4(field_data, all_data):
|
def isValidIPAddress4(field_data, all_data):
|
||||||
if not ip4_re.search(field_data):
|
if not ip4_re.search(field_data):
|
||||||
raise ValidationError, _("Please enter a valid IP address.")
|
raise ValidationError, gettext("Please enter a valid IP address.")
|
||||||
|
|
||||||
def isNotEmpty(field_data, all_data):
|
def isNotEmpty(field_data, all_data):
|
||||||
if field_data.strip() == '':
|
if field_data.strip() == '':
|
||||||
raise ValidationError, _("Empty values are not allowed here.")
|
raise ValidationError, gettext("Empty values are not allowed here.")
|
||||||
|
|
||||||
def isOnlyDigits(field_data, all_data):
|
def isOnlyDigits(field_data, all_data):
|
||||||
if not field_data.isdigit():
|
if not field_data.isdigit():
|
||||||
raise ValidationError, _("Non-numeric characters aren't allowed here.")
|
raise ValidationError, gettext("Non-numeric characters aren't allowed here.")
|
||||||
|
|
||||||
def isNotOnlyDigits(field_data, all_data):
|
def isNotOnlyDigits(field_data, all_data):
|
||||||
if field_data.isdigit():
|
if field_data.isdigit():
|
||||||
raise ValidationError, _("This value can't be comprised solely of digits.")
|
raise ValidationError, gettext("This value can't be comprised solely of digits.")
|
||||||
|
|
||||||
def isInteger(field_data, all_data):
|
def isInteger(field_data, all_data):
|
||||||
# This differs from isOnlyDigits because this accepts the negative sign
|
# This differs from isOnlyDigits because this accepts the negative sign
|
||||||
if not integer_re.search(field_data):
|
if not integer_re.search(field_data):
|
||||||
raise ValidationError, _("Enter a whole number.")
|
raise ValidationError, gettext("Enter a whole number.")
|
||||||
|
|
||||||
def isOnlyLetters(field_data, all_data):
|
def isOnlyLetters(field_data, all_data):
|
||||||
if not field_data.isalpha():
|
if not field_data.isalpha():
|
||||||
raise ValidationError, _("Only alphabetical characters are allowed here.")
|
raise ValidationError, gettext("Only alphabetical characters are allowed here.")
|
||||||
|
|
||||||
def isValidANSIDate(field_data, all_data):
|
def isValidANSIDate(field_data, all_data):
|
||||||
if not ansi_date_re.search(field_data):
|
if not ansi_date_re.search(field_data):
|
||||||
raise ValidationError, _('Enter a valid date in YYYY-MM-DD format.')
|
raise ValidationError, gettext('Enter a valid date in YYYY-MM-DD format.')
|
||||||
|
|
||||||
def isValidANSITime(field_data, all_data):
|
def isValidANSITime(field_data, all_data):
|
||||||
if not ansi_time_re.search(field_data):
|
if not ansi_time_re.search(field_data):
|
||||||
raise ValidationError, _('Enter a valid time in HH:MM format.')
|
raise ValidationError, gettext('Enter a valid time in HH:MM format.')
|
||||||
|
|
||||||
def isValidANSIDatetime(field_data, all_data):
|
def isValidANSIDatetime(field_data, all_data):
|
||||||
if not ansi_datetime_re.search(field_data):
|
if not ansi_datetime_re.search(field_data):
|
||||||
raise ValidationError, _('Enter a valid date/time in YYYY-MM-DD HH:MM format.')
|
raise ValidationError, gettext('Enter a valid date/time in YYYY-MM-DD HH:MM format.')
|
||||||
|
|
||||||
def isValidEmail(field_data, all_data):
|
def isValidEmail(field_data, all_data):
|
||||||
if not email_re.search(field_data):
|
if not email_re.search(field_data):
|
||||||
raise ValidationError, _('Enter a valid e-mail address.')
|
raise ValidationError, gettext('Enter a valid e-mail address.')
|
||||||
|
|
||||||
def isValidImage(field_data, all_data):
|
def isValidImage(field_data, all_data):
|
||||||
"""
|
"""
|
||||||
@ -147,18 +146,18 @@ def isValidImage(field_data, all_data):
|
|||||||
try:
|
try:
|
||||||
Image.open(StringIO(field_data['content']))
|
Image.open(StringIO(field_data['content']))
|
||||||
except IOError: # Python Imaging Library doesn't recognize it as an image
|
except IOError: # Python Imaging Library doesn't recognize it as an image
|
||||||
raise ValidationError, _("Upload a valid image. The file you uploaded was either not an image or a corrupted image.")
|
raise ValidationError, gettext("Upload a valid image. The file you uploaded was either not an image or a corrupted image.")
|
||||||
|
|
||||||
def isValidImageURL(field_data, all_data):
|
def isValidImageURL(field_data, all_data):
|
||||||
uc = URLMimeTypeCheck(('image/jpeg', 'image/gif', 'image/png'))
|
uc = URLMimeTypeCheck(('image/jpeg', 'image/gif', 'image/png'))
|
||||||
try:
|
try:
|
||||||
uc(field_data, all_data)
|
uc(field_data, all_data)
|
||||||
except URLMimeTypeCheck.InvalidContentType:
|
except URLMimeTypeCheck.InvalidContentType:
|
||||||
raise ValidationError, _("The URL %s does not point to a valid image.") % field_data
|
raise ValidationError, gettext("The URL %s does not point to a valid image.") % field_data
|
||||||
|
|
||||||
def isValidPhone(field_data, all_data):
|
def isValidPhone(field_data, all_data):
|
||||||
if not phone_re.search(field_data):
|
if not phone_re.search(field_data):
|
||||||
raise ValidationError, _('Phone numbers must be in XXX-XXX-XXXX format. "%s" is invalid.') % field_data
|
raise ValidationError, gettext('Phone numbers must be in XXX-XXX-XXXX format. "%s" is invalid.') % field_data
|
||||||
|
|
||||||
def isValidQuicktimeVideoURL(field_data, all_data):
|
def isValidQuicktimeVideoURL(field_data, all_data):
|
||||||
"Checks that the given URL is a video that can be played by QuickTime (qt, mpeg)"
|
"Checks that the given URL is a video that can be played by QuickTime (qt, mpeg)"
|
||||||
@ -166,11 +165,11 @@ def isValidQuicktimeVideoURL(field_data, all_data):
|
|||||||
try:
|
try:
|
||||||
uc(field_data, all_data)
|
uc(field_data, all_data)
|
||||||
except URLMimeTypeCheck.InvalidContentType:
|
except URLMimeTypeCheck.InvalidContentType:
|
||||||
raise ValidationError, _("The URL %s does not point to a valid QuickTime video.") % field_data
|
raise ValidationError, gettext("The URL %s does not point to a valid QuickTime video.") % field_data
|
||||||
|
|
||||||
def isValidURL(field_data, all_data):
|
def isValidURL(field_data, all_data):
|
||||||
if not url_re.search(field_data):
|
if not url_re.search(field_data):
|
||||||
raise ValidationError, _("A valid URL is required.")
|
raise ValidationError, gettext("A valid URL is required.")
|
||||||
|
|
||||||
def isValidHTML(field_data, all_data):
|
def isValidHTML(field_data, all_data):
|
||||||
import urllib, urllib2
|
import urllib, urllib2
|
||||||
@ -184,14 +183,14 @@ def isValidHTML(field_data, all_data):
|
|||||||
return
|
return
|
||||||
from xml.dom.minidom import parseString
|
from xml.dom.minidom import parseString
|
||||||
error_messages = [e.firstChild.wholeText for e in parseString(u.read()).getElementsByTagName('messages')[0].getElementsByTagName('msg')]
|
error_messages = [e.firstChild.wholeText for e in parseString(u.read()).getElementsByTagName('messages')[0].getElementsByTagName('msg')]
|
||||||
raise ValidationError, _("Valid HTML is required. Specific errors are:\n%s") % "\n".join(error_messages)
|
raise ValidationError, gettext("Valid HTML is required. Specific errors are:\n%s") % "\n".join(error_messages)
|
||||||
|
|
||||||
def isWellFormedXml(field_data, all_data):
|
def isWellFormedXml(field_data, all_data):
|
||||||
from xml.dom.minidom import parseString
|
from xml.dom.minidom import parseString
|
||||||
try:
|
try:
|
||||||
parseString(field_data)
|
parseString(field_data)
|
||||||
except Exception, e: # Naked except because we're not sure what will be thrown
|
except Exception, e: # Naked except because we're not sure what will be thrown
|
||||||
raise ValidationError, _("Badly formed XML: %s") % str(e)
|
raise ValidationError, gettext("Badly formed XML: %s") % str(e)
|
||||||
|
|
||||||
def isWellFormedXmlFragment(field_data, all_data):
|
def isWellFormedXmlFragment(field_data, all_data):
|
||||||
isWellFormedXml('<root>%s</root>' % field_data, all_data)
|
isWellFormedXml('<root>%s</root>' % field_data, all_data)
|
||||||
@ -201,19 +200,19 @@ def isExistingURL(field_data, all_data):
|
|||||||
try:
|
try:
|
||||||
u = urllib2.urlopen(field_data)
|
u = urllib2.urlopen(field_data)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
raise ValidationError, _("Invalid URL: %s") % field_data
|
raise ValidationError, gettext("Invalid URL: %s") % field_data
|
||||||
except urllib2.HTTPError, e:
|
except urllib2.HTTPError, e:
|
||||||
# 401s are valid; they just mean authorization is required.
|
# 401s are valid; they just mean authorization is required.
|
||||||
if e.code not in ('401',):
|
if e.code not in ('401',):
|
||||||
raise ValidationError, _("The URL %s is a broken link.") % field_data
|
raise ValidationError, gettext("The URL %s is a broken link.") % field_data
|
||||||
except: # urllib2.URLError, httplib.InvalidURL, etc.
|
except: # urllib2.URLError, httplib.InvalidURL, etc.
|
||||||
raise ValidationError, _("The URL %s is a broken link.") % field_data
|
raise ValidationError, gettext("The URL %s is a broken link.") % field_data
|
||||||
|
|
||||||
def isValidUSState(field_data, all_data):
|
def isValidUSState(field_data, all_data):
|
||||||
"Checks that the given string is a valid two-letter U.S. state abbreviation"
|
"Checks that the given string is a valid two-letter U.S. state abbreviation"
|
||||||
states = ['AA', 'AE', 'AK', 'AL', 'AP', 'AR', 'AS', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'FM', 'GA', 'GU', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MH', 'MI', 'MN', 'MO', 'MP', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'PR', 'PW', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VI', 'VT', 'WA', 'WI', 'WV', 'WY']
|
states = ['AA', 'AE', 'AK', 'AL', 'AP', 'AR', 'AS', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'FM', 'GA', 'GU', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MH', 'MI', 'MN', 'MO', 'MP', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'PR', 'PW', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VI', 'VT', 'WA', 'WI', 'WV', 'WY']
|
||||||
if field_data.upper() not in states:
|
if field_data.upper() not in states:
|
||||||
raise ValidationError, _("Enter a valid U.S. state abbreviation.")
|
raise ValidationError, gettext("Enter a valid U.S. state abbreviation.")
|
||||||
|
|
||||||
def hasNoProfanities(field_data, all_data):
|
def hasNoProfanities(field_data, all_data):
|
||||||
"""
|
"""
|
||||||
@ -335,7 +334,7 @@ class IsAPowerOf:
|
|||||||
from math import log
|
from math import log
|
||||||
val = log(int(field_data)) / log(self.power_of)
|
val = log(int(field_data)) / log(self.power_of)
|
||||||
if val != int(val):
|
if val != int(val):
|
||||||
raise ValidationError, _("This value must be a power of %s.") % self.power_of
|
raise ValidationError, gettext("This value must be a power of %s.") % self.power_of
|
||||||
|
|
||||||
class IsValidFloat:
|
class IsValidFloat:
|
||||||
def __init__(self, max_digits, decimal_places):
|
def __init__(self, max_digits, decimal_places):
|
||||||
@ -346,9 +345,9 @@ class IsValidFloat:
|
|||||||
try:
|
try:
|
||||||
float(data)
|
float(data)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
raise ValidationError, _("Please enter a valid decimal number.")
|
raise ValidationError, gettext("Please enter a valid decimal number.")
|
||||||
if len(data) > (self.max_digits + 1):
|
if len(data) > (self.max_digits + 1):
|
||||||
raise ValidationError, ngettext( "Please enter a valid decimal number with at most %s total digit.",
|
raise ValidationError, ngettext("Please enter a valid decimal number with at most %s total digit.",
|
||||||
"Please enter a valid decimal number with at most %s total digits.", self.max_digits) % self.max_digits
|
"Please enter a valid decimal number with at most %s total digits.", self.max_digits) % self.max_digits
|
||||||
if '.' in data and len(data.split('.')[1]) > self.decimal_places:
|
if '.' in data and len(data.split('.')[1]) > self.decimal_places:
|
||||||
raise ValidationError, ngettext("Please enter a valid decimal number with at most %s decimal place.",
|
raise ValidationError, ngettext("Please enter a valid decimal number with at most %s decimal place.",
|
||||||
@ -425,10 +424,10 @@ class URLMimeTypeCheck:
|
|||||||
try:
|
try:
|
||||||
info = urllib2.urlopen(field_data).info()
|
info = urllib2.urlopen(field_data).info()
|
||||||
except (urllib2.HTTPError, urllib2.URLError):
|
except (urllib2.HTTPError, urllib2.URLError):
|
||||||
raise URLMimeTypeCheck.CouldNotRetrieve, _("Could not retrieve anything from %s.") % field_data
|
raise URLMimeTypeCheck.CouldNotRetrieve, gettext("Could not retrieve anything from %s.") % field_data
|
||||||
content_type = info['content-type']
|
content_type = info['content-type']
|
||||||
if content_type not in self.mime_type_list:
|
if content_type not in self.mime_type_list:
|
||||||
raise URLMimeTypeCheck.InvalidContentType, _("The URL %(url)s returned the invalid Content-Type header '%(contenttype)s'.") % {
|
raise URLMimeTypeCheck.InvalidContentType, gettext("The URL %(url)s returned the invalid Content-Type header '%(contenttype)s'.") % {
|
||||||
'url': field_data, 'contenttype': content_type}
|
'url': field_data, 'contenttype': content_type}
|
||||||
|
|
||||||
class RelaxNGCompact:
|
class RelaxNGCompact:
|
||||||
|
Loading…
x
Reference in New Issue
Block a user