Ticket #4152: 4152.2.cumulative.diff
File 4152.2.cumulative.diff, 44.6 KB (added by , 18 years ago) |
---|
-
django/oldforms/__init__.py
2 2 from django.core.exceptions import PermissionDenied 3 3 from django.utils.html import escape 4 4 from django.conf import settings 5 from django.utils.translation import gettext,ngettext5 from django.utils.translation import ugettext, ungettext 6 6 7 7 FORM_FIELD_ID_PREFIX = 'id_' 8 8 … … 66 66 errors.setdefault(field.field_name, []).extend(e.messages) 67 67 68 68 # if field.is_required and not new_data.get(field.field_name, False): 69 # errors.setdefault(field.field_name, []).append( gettext_lazy('This field is required.'))69 # errors.setdefault(field.field_name, []).append(ugettext_lazy('This field is required.')) 70 70 # continue 71 71 # try: 72 72 # validator_list = field.validator_list … … 354 354 def get_validation_errors(self, new_data): 355 355 errors = {} 356 356 if self.is_required and not new_data.get(self.field_name, False): 357 errors.setdefault(self.field_name, []).append( gettext('This field is required.'))357 errors.setdefault(self.field_name, []).append(ugettext('This field is required.')) 358 358 return errors 359 359 try: 360 360 for validator in self.validator_list: … … 389 389 390 390 def isValidLength(self, data, form): 391 391 if data and self.maxlength and len(data.decode(settings.DEFAULT_CHARSET)) > self.maxlength: 392 raise validators.ValidationError, ngettext("Ensure your text is less than %s character.",392 raise validators.ValidationError, ungettext("Ensure your text is less than %s character.", 393 393 "Ensure your text is less than %s characters.", self.maxlength) % self.maxlength 394 394 395 395 def hasNoNewlines(self, data, form): 396 396 if data and '\n' in data: 397 raise validators.ValidationError, gettext("Line breaks are not allowed here.")397 raise validators.ValidationError, ugettext("Line breaks are not allowed here.") 398 398 399 399 def render(self, data): 400 400 if data is None: … … 495 495 str_data = str(data) 496 496 str_choices = [str(item[0]) for item in self.choices] 497 497 if str_data not in str_choices: 498 raise validators.ValidationError, gettext("Select a valid choice; '%(data)s' is not in %(choices)s.") % {'data': str_data, 'choices': str_choices}498 raise validators.ValidationError, ugettext("Select a valid choice; '%(data)s' is not in %(choices)s.") % {'data': str_data, 'choices': str_choices} 499 499 500 500 class NullSelectField(SelectField): 501 501 "This SelectField converts blank fields to None" … … 568 568 str_data = str(data) 569 569 str_choices = [str(item[0]) for item in self.choices] 570 570 if str_data not in str_choices: 571 raise validators.ValidationError, gettext("Select a valid choice; '%(data)s' is not in %(choices)s.") % {'data':str_data, 'choices':str_choices}571 raise validators.ValidationError, ugettext("Select a valid choice; '%(data)s' is not in %(choices)s.") % {'data':str_data, 'choices':str_choices} 572 572 573 573 class NullBooleanField(SelectField): 574 574 "This SelectField provides 'Yes', 'No' and 'Unknown', mapping results to True, False or None" … … 607 607 str_choices = [str(item[0]) for item in self.choices] 608 608 for val in map(str, field_data): 609 609 if val not in str_choices: 610 raise validators.ValidationError, gettext("Select a valid choice; '%(data)s' is not in %(choices)s.") % {'data':val, 'choices':str_choices}610 raise validators.ValidationError, ugettext("Select a valid choice; '%(data)s' is not in %(choices)s.") % {'data':val, 'choices':str_choices} 611 611 612 612 def html2python(data): 613 613 if data is None: … … 669 669 try: 670 670 content = field_data['content'] 671 671 except TypeError: 672 raise validators.CriticalValidationError, gettext("No file was submitted. Check the encoding type on the form.")672 raise validators.CriticalValidationError, ugettext("No file was submitted. Check the encoding type on the form.") 673 673 if not content: 674 raise validators.CriticalValidationError, gettext("The submitted file is empty.")674 raise validators.CriticalValidationError, ugettext("The submitted file is empty.") 675 675 676 676 def render(self, data): 677 677 return '<input type="file" id="%s" class="v%s" name="%s" />' % \ … … 727 727 728 728 def isSmallInteger(self, field_data, all_data): 729 729 if not -32768 <= int(field_data) <= 32767: 730 raise validators.CriticalValidationError, gettext("Enter a whole number between -32,768 and 32,767.")730 raise validators.CriticalValidationError, ugettext("Enter a whole number between -32,768 and 32,767.") 731 731 732 732 class PositiveIntegerField(IntegerField): 733 733 def __init__(self, field_name, length=10, maxlength=None, is_required=False, validator_list=None): … … 737 737 738 738 def isPositive(self, field_data, all_data): 739 739 if int(field_data) < 0: 740 raise validators.CriticalValidationError, gettext("Enter a positive number.")740 raise validators.CriticalValidationError, ugettext("Enter a positive number.") 741 741 742 742 class PositiveSmallIntegerField(IntegerField): 743 743 def __init__(self, field_name, length=5, maxlength=None, is_required=False, validator_list=None): … … 747 747 748 748 def isPositiveSmall(self, field_data, all_data): 749 749 if not 0 <= int(field_data) <= 32767: 750 raise validators.CriticalValidationError, gettext("Enter a whole number between 0 and 32,767.")750 raise validators.CriticalValidationError, ugettext("Enter a whole number between 0 and 32,767.") 751 751 752 752 class FloatField(TextField): 753 753 def __init__(self, field_name, max_digits, decimal_places, is_required=False, validator_list=None): -
django/db/models/fields/__init__.py
8 8 from django.utils.functional import curry 9 9 from django.utils.itercompat import tee 10 10 from django.utils.text import capfirst 11 from django.utils.translation import gettext,gettext_lazy11 from django.utils.translation import ugettext, ugettext_lazy 12 12 import datetime, os, time 13 13 14 14 class NOT_PROVIDED: … … 39 39 return 40 40 if getattr(self, 'original_object', None) and self.original_object._get_pk_val() == old_obj._get_pk_val(): 41 41 return 42 raise validators.ValidationError, gettext("%(optname)s with this %(fieldname)s already exists.") % {'optname': capfirst(opts.verbose_name), 'fieldname': f.verbose_name}42 raise validators.ValidationError, ugettext("%(optname)s with this %(fieldname)s already exists.") % {'optname': capfirst(opts.verbose_name), 'fieldname': f.verbose_name} 43 43 44 44 # A guide to Field parameters: 45 45 # … … 114 114 Subclasses should implement validate(), not validate_full(). 115 115 """ 116 116 if not self.blank and not field_data: 117 return [ gettext_lazy('This field is required.')]117 return [ugettext_lazy('This field is required.')] 118 118 try: 119 119 self.validate(field_data, all_data) 120 120 except validators.ValidationError, e: … … 271 271 core_field_names.extend(f.get_manipulator_field_names(name_prefix)) 272 272 # Now, if there are any, add the validator to this FormField. 273 273 if core_field_names: 274 params['validator_list'].append(validators.RequiredIfOtherFieldsGiven(core_field_names, gettext_lazy("This field is required.")))274 params['validator_list'].append(validators.RequiredIfOtherFieldsGiven(core_field_names, ugettext_lazy("This field is required."))) 275 275 276 276 # Finally, add the field_names. 277 277 field_names = self.get_manipulator_field_names(name_prefix) … … 364 364 try: 365 365 return int(value) 366 366 except (TypeError, ValueError): 367 raise validators.ValidationError, gettext("This value must be an integer.")367 raise validators.ValidationError, ugettext("This value must be an integer.") 368 368 369 369 def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True): 370 370 if not rel: … … 399 399 if value in (True, False): return value 400 400 if value in ('t', 'True', '1'): return True 401 401 if value in ('f', 'False', '0'): return False 402 raise validators.ValidationError, gettext("This value must be either True or False.")402 raise validators.ValidationError, ugettext("This value must be either True or False.") 403 403 404 404 def get_manipulator_field_objs(self): 405 405 return [oldforms.CheckboxField] … … 420 420 if self.null: 421 421 return value 422 422 else: 423 raise validators.ValidationError, gettext_lazy("This field cannot be null.")423 raise validators.ValidationError, ugettext_lazy("This field cannot be null.") 424 424 return str(value) 425 425 426 426 def formfield(self, **kwargs): … … 454 454 try: 455 455 return datetime.date(*time.strptime(value, '%Y-%m-%d')[:3]) 456 456 except ValueError: 457 raise validators.ValidationError, gettext('Enter a valid date in YYYY-MM-DD format.')457 raise validators.ValidationError, ugettext('Enter a valid date in YYYY-MM-DD format.') 458 458 459 459 def get_db_prep_lookup(self, lookup_type, value): 460 460 if lookup_type == 'range': … … 523 523 try: 524 524 return datetime.datetime(*time.strptime(value, '%Y-%m-%d')[:3]) 525 525 except ValueError: 526 raise validators.ValidationError, gettext('Enter a valid date/time in YYYY-MM-DD HH:MM format.')526 raise validators.ValidationError, ugettext('Enter a valid date/time in YYYY-MM-DD HH:MM format.') 527 527 528 528 def get_db_prep_save(self, value): 529 529 # Casts dates into string format for entry into database. … … 607 607 self.always_test = True 608 608 def __call__(self, field_data, all_data): 609 609 if not all_data.get(self.other_file_field_name, False): 610 c = validators.RequiredIfOtherFieldsGiven(self.other_field_names, gettext_lazy("This field is required."))610 c = validators.RequiredIfOtherFieldsGiven(self.other_field_names, ugettext_lazy("This field is required.")) 611 611 c(field_data, all_data) 612 612 # First, get the core fields, if any. 613 613 core_field_names = [] … … 618 618 if core_field_names: 619 619 field_list[0].validator_list.append(RequiredFileField(core_field_names, field_list[1].field_name)) 620 620 else: 621 v = validators.RequiredIfOtherFieldNotGiven(field_list[1].field_name, gettext_lazy("This field is required."))621 v = validators.RequiredIfOtherFieldNotGiven(field_list[1].field_name, ugettext_lazy("This field is required.")) 622 622 v.always_test = True 623 623 field_list[0].validator_list.append(v) 624 624 field_list[0].is_required = field_list[1].is_required = False … … 748 748 if value in ('None'): return None 749 749 if value in ('t', 'True', '1'): return True 750 750 if value in ('f', 'False', '0'): return False 751 raise validators.ValidationError, gettext("This value must be either None, True or False.")751 raise validators.ValidationError, ugettext("This value must be either None, True or False.") 752 752 753 753 def get_manipulator_field_objs(self): 754 754 return [oldforms.NullBooleanField] -
django/core/validators.py
10 10 11 11 import urllib2 12 12 from django.conf import settings 13 from django.utils.translation import gettext, gettext_lazy,ngettext13 from django.utils.translation import ugettext, ugettext_lazy, ungettext 14 14 from django.utils.functional import Promise, lazy 15 15 import re 16 16 … … 61 61 62 62 def isAlphaNumeric(field_data, all_data): 63 63 if not alnum_re.search(field_data): 64 raise ValidationError, gettext("This value must contain only letters, numbers and underscores.")64 raise ValidationError, ugettext("This value must contain only letters, numbers and underscores.") 65 65 66 66 def isAlphaNumericURL(field_data, all_data): 67 67 if not alnumurl_re.search(field_data): 68 raise ValidationError, gettext("This value must contain only letters, numbers, underscores, dashes or slashes.")68 raise ValidationError, ugettext("This value must contain only letters, numbers, underscores, dashes or slashes.") 69 69 70 70 def isSlug(field_data, all_data): 71 71 if not slug_re.search(field_data): 72 raise ValidationError, gettext("This value must contain only letters, numbers, underscores or hyphens.")72 raise ValidationError, ugettext("This value must contain only letters, numbers, underscores or hyphens.") 73 73 74 74 def isLowerCase(field_data, all_data): 75 75 if field_data.lower() != field_data: 76 raise ValidationError, gettext("Uppercase letters are not allowed here.")76 raise ValidationError, ugettext("Uppercase letters are not allowed here.") 77 77 78 78 def isUpperCase(field_data, all_data): 79 79 if field_data.upper() != field_data: 80 raise ValidationError, gettext("Lowercase letters are not allowed here.")80 raise ValidationError, ugettext("Lowercase letters are not allowed here.") 81 81 82 82 def isCommaSeparatedIntegerList(field_data, all_data): 83 83 for supposed_int in field_data.split(','): 84 84 try: 85 85 int(supposed_int) 86 86 except ValueError: 87 raise ValidationError, gettext("Enter only digits separated by commas.")87 raise ValidationError, ugettext("Enter only digits separated by commas.") 88 88 89 89 def isCommaSeparatedEmailList(field_data, all_data): 90 90 """ … … 96 96 try: 97 97 isValidEmail(supposed_email.strip(), '') 98 98 except ValidationError: 99 raise ValidationError, gettext("Enter valid e-mail addresses separated by commas.")99 raise ValidationError, ugettext("Enter valid e-mail addresses separated by commas.") 100 100 101 101 def isValidIPAddress4(field_data, all_data): 102 102 if not ip4_re.search(field_data): 103 raise ValidationError, gettext("Please enter a valid IP address.")103 raise ValidationError, ugettext("Please enter a valid IP address.") 104 104 105 105 def isNotEmpty(field_data, all_data): 106 106 if field_data.strip() == '': 107 raise ValidationError, gettext("Empty values are not allowed here.")107 raise ValidationError, ugettext("Empty values are not allowed here.") 108 108 109 109 def isOnlyDigits(field_data, all_data): 110 110 if not field_data.isdigit(): 111 raise ValidationError, gettext("Non-numeric characters aren't allowed here.")111 raise ValidationError, ugettext("Non-numeric characters aren't allowed here.") 112 112 113 113 def isNotOnlyDigits(field_data, all_data): 114 114 if field_data.isdigit(): 115 raise ValidationError, gettext("This value can't be comprised solely of digits.")115 raise ValidationError, ugettext("This value can't be comprised solely of digits.") 116 116 117 117 def isInteger(field_data, all_data): 118 118 # This differs from isOnlyDigits because this accepts the negative sign 119 119 if not integer_re.search(field_data): 120 raise ValidationError, gettext("Enter a whole number.")120 raise ValidationError, ugettext("Enter a whole number.") 121 121 122 122 def isOnlyLetters(field_data, all_data): 123 123 if not field_data.isalpha(): 124 raise ValidationError, gettext("Only alphabetical characters are allowed here.")124 raise ValidationError, ugettext("Only alphabetical characters are allowed here.") 125 125 126 126 def _isValidDate(date_string): 127 127 """ … … 136 136 # This check is needed because strftime is used when saving the date 137 137 # value to the database, and strftime requires that the year be >=1900. 138 138 if year < 1900: 139 raise ValidationError, gettext('Year must be 1900 or later.')139 raise ValidationError, ugettext('Year must be 1900 or later.') 140 140 try: 141 141 date(year, month, day) 142 142 except ValueError, e: 143 msg = gettext('Invalid date: %s') %gettext(str(e))143 msg = ugettext('Invalid date: %s') % ugettext(str(e)) 144 144 raise ValidationError, msg 145 145 146 146 def isValidANSIDate(field_data, all_data): 147 147 if not ansi_date_re.search(field_data): 148 raise ValidationError, gettext('Enter a valid date in YYYY-MM-DD format.')148 raise ValidationError, ugettext('Enter a valid date in YYYY-MM-DD format.') 149 149 _isValidDate(field_data) 150 150 151 151 def isValidANSITime(field_data, all_data): 152 152 if not ansi_time_re.search(field_data): 153 raise ValidationError, gettext('Enter a valid time in HH:MM format.')153 raise ValidationError, ugettext('Enter a valid time in HH:MM format.') 154 154 155 155 def isValidANSIDatetime(field_data, all_data): 156 156 if not ansi_datetime_re.search(field_data): 157 raise ValidationError, gettext('Enter a valid date/time in YYYY-MM-DD HH:MM format.')157 raise ValidationError, ugettext('Enter a valid date/time in YYYY-MM-DD HH:MM format.') 158 158 _isValidDate(field_data.split()[0]) 159 159 160 160 def isValidEmail(field_data, all_data): 161 161 if not email_re.search(field_data): 162 raise ValidationError, gettext('Enter a valid e-mail address.')162 raise ValidationError, ugettext('Enter a valid e-mail address.') 163 163 164 164 def isValidImage(field_data, all_data): 165 165 """ … … 171 171 try: 172 172 content = field_data['content'] 173 173 except TypeError: 174 raise ValidationError, gettext("No file was submitted. Check the encoding type on the form.")174 raise ValidationError, ugettext("No file was submitted. Check the encoding type on the form.") 175 175 try: 176 176 Image.open(StringIO(content)) 177 177 except IOError: # Python Imaging Library doesn't recognize it as an image 178 raise ValidationError, gettext("Upload a valid image. The file you uploaded was either not an image or a corrupted image.")178 raise ValidationError, ugettext("Upload a valid image. The file you uploaded was either not an image or a corrupted image.") 179 179 180 180 def isValidImageURL(field_data, all_data): 181 181 uc = URLMimeTypeCheck(('image/jpeg', 'image/gif', 'image/png')) 182 182 try: 183 183 uc(field_data, all_data) 184 184 except URLMimeTypeCheck.InvalidContentType: 185 raise ValidationError, gettext("The URL %s does not point to a valid image.") % field_data185 raise ValidationError, ugettext("The URL %s does not point to a valid image.") % field_data 186 186 187 187 def isValidPhone(field_data, all_data): 188 188 if not phone_re.search(field_data): 189 raise ValidationError, gettext('Phone numbers must be in XXX-XXX-XXXX format. "%s" is invalid.') % field_data189 raise ValidationError, ugettext('Phone numbers must be in XXX-XXX-XXXX format. "%s" is invalid.') % field_data 190 190 191 191 def isValidQuicktimeVideoURL(field_data, all_data): 192 192 "Checks that the given URL is a video that can be played by QuickTime (qt, mpeg)" … … 194 194 try: 195 195 uc(field_data, all_data) 196 196 except URLMimeTypeCheck.InvalidContentType: 197 raise ValidationError, gettext("The URL %s does not point to a valid QuickTime video.") % field_data197 raise ValidationError, ugettext("The URL %s does not point to a valid QuickTime video.") % field_data 198 198 199 199 def isValidURL(field_data, all_data): 200 200 if not url_re.search(field_data): 201 raise ValidationError, gettext("A valid URL is required.")201 raise ValidationError, ugettext("A valid URL is required.") 202 202 203 203 def isValidHTML(field_data, all_data): 204 204 import urllib, urllib2 … … 212 212 return 213 213 from xml.dom.minidom import parseString 214 214 error_messages = [e.firstChild.wholeText for e in parseString(u.read()).getElementsByTagName('messages')[0].getElementsByTagName('msg')] 215 raise ValidationError, gettext("Valid HTML is required. Specific errors are:\n%s") % "\n".join(error_messages)215 raise ValidationError, ugettext("Valid HTML is required. Specific errors are:\n%s") % "\n".join(error_messages) 216 216 217 217 def isWellFormedXml(field_data, all_data): 218 218 from xml.dom.minidom import parseString 219 219 try: 220 220 parseString(field_data) 221 221 except Exception, e: # Naked except because we're not sure what will be thrown 222 raise ValidationError, gettext("Badly formed XML: %s") % str(e)222 raise ValidationError, ugettext("Badly formed XML: %s") % str(e) 223 223 224 224 def isWellFormedXmlFragment(field_data, all_data): 225 225 isWellFormedXml('<root>%s</root>' % field_data, all_data) … … 249 249 "Checks that the given string is a valid two-letter U.S. state abbreviation" 250 250 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'] 251 251 if field_data.upper() not in states: 252 raise ValidationError, gettext("Enter a valid U.S. state abbreviation.")252 raise ValidationError, ugettext("Enter a valid U.S. state abbreviation.") 253 253 254 254 def hasNoProfanities(field_data, all_data): 255 255 """ … … 263 263 if words_seen: 264 264 from django.utils.text import get_text_list 265 265 plural = len(words_seen) > 1 266 raise ValidationError, ngettext("Watch your mouth! The word %s is not allowed here.",266 raise ValidationError, ungettext("Watch your mouth! The word %s is not allowed here.", 267 267 "Watch your mouth! The words %s are not allowed here.", plural) % \ 268 268 get_text_list(['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in words_seen], 'and') 269 269 270 270 class AlwaysMatchesOtherField(object): 271 271 def __init__(self, other_field_name, error_message=None): 272 272 self.other = other_field_name 273 self.error_message = error_message or lazy_inter( gettext_lazy("This field must match the '%s' field."), self.other)273 self.error_message = error_message or lazy_inter(ugettext_lazy("This field must match the '%s' field."), self.other) 274 274 self.always_test = True 275 275 276 276 def __call__(self, field_data, all_data): … … 289 289 v(field_data, all_data) 290 290 291 291 class RequiredIfOtherFieldNotGiven(object): 292 def __init__(self, other_field_name, error_message= gettext_lazy("Please enter something for at least one field.")):292 def __init__(self, other_field_name, error_message=ugettext_lazy("Please enter something for at least one field.")): 293 293 self.other, self.error_message = other_field_name, error_message 294 294 self.always_test = True 295 295 … … 298 298 raise ValidationError, self.error_message 299 299 300 300 class RequiredIfOtherFieldsGiven(object): 301 def __init__(self, other_field_names, error_message= gettext_lazy("Please enter both fields or leave them both empty.")):301 def __init__(self, other_field_names, error_message=ugettext_lazy("Please enter both fields or leave them both empty.")): 302 302 self.other, self.error_message = other_field_names, error_message 303 303 self.always_test = True 304 304 … … 309 309 310 310 class RequiredIfOtherFieldGiven(RequiredIfOtherFieldsGiven): 311 311 "Like RequiredIfOtherFieldsGiven, but takes a single field name instead of a list." 312 def __init__(self, other_field_name, error_message= gettext_lazy("Please enter both fields or leave them both empty.")):312 def __init__(self, other_field_name, error_message=ugettext_lazy("Please enter both fields or leave them both empty.")): 313 313 RequiredIfOtherFieldsGiven.__init__(self, [other_field_name], error_message) 314 314 315 315 class RequiredIfOtherFieldEquals(object): … … 317 317 self.other_field = other_field 318 318 self.other_value = other_value 319 319 other_label = other_label or other_value 320 self.error_message = error_message or lazy_inter( gettext_lazy("This field must be given if %(field)s is %(value)s"), {320 self.error_message = error_message or lazy_inter(ugettext_lazy("This field must be given if %(field)s is %(value)s"), { 321 321 'field': other_field, 'value': other_label}) 322 322 self.always_test = True 323 323 … … 330 330 self.other_field = other_field 331 331 self.other_value = other_value 332 332 other_label = other_label or other_value 333 self.error_message = error_message or lazy_inter( gettext_lazy("This field must be given if %(field)s is not %(value)s"), {333 self.error_message = error_message or lazy_inter(ugettext_lazy("This field must be given if %(field)s is not %(value)s"), { 334 334 'field': other_field, 'value': other_label}) 335 335 self.always_test = True 336 336 … … 349 349 class UniqueAmongstFieldsWithPrefix(object): 350 350 def __init__(self, field_name, prefix, error_message): 351 351 self.field_name, self.prefix = field_name, prefix 352 self.error_message = error_message or gettext_lazy("Duplicate values are not allowed.")352 self.error_message = error_message or ugettext_lazy("Duplicate values are not allowed.") 353 353 354 354 def __call__(self, field_data, all_data): 355 355 for field_name, value in all_data.items(): … … 364 364 self.lower, self.upper = lower, upper 365 365 if not error_message: 366 366 if lower and upper: 367 self.error_message = gettext("This value must be between %(lower)s and %(upper)s.") % {'lower': lower, 'upper': upper}367 self.error_message = ugettext("This value must be between %(lower)s and %(upper)s.") % {'lower': lower, 'upper': upper} 368 368 elif lower: 369 self.error_message = gettext("This value must be at least %s.") % lower369 self.error_message = ugettext("This value must be at least %s.") % lower 370 370 elif upper: 371 self.error_message = gettext("This value must be no more than %s.") % upper371 self.error_message = ugettext("This value must be no more than %s.") % upper 372 372 else: 373 373 self.error_message = error_message 374 374 … … 404 404 from math import log 405 405 val = log(int(field_data)) / log(self.power_of) 406 406 if val != int(val): 407 raise ValidationError, gettext("This value must be a power of %s.") % self.power_of407 raise ValidationError, ugettext("This value must be a power of %s.") % self.power_of 408 408 409 409 class IsValidFloat(object): 410 410 def __init__(self, max_digits, decimal_places): … … 415 415 try: 416 416 float(data) 417 417 except ValueError: 418 raise ValidationError, gettext("Please enter a valid decimal number.")418 raise ValidationError, ugettext("Please enter a valid decimal number.") 419 419 # Negative floats require more space to input. 420 420 max_allowed_length = data.startswith('-') and (self.max_digits + 2) or (self.max_digits + 1) 421 421 if len(data) > max_allowed_length: 422 raise ValidationError, ngettext("Please enter a valid decimal number with at most %s total digit.",422 raise ValidationError, ungettext("Please enter a valid decimal number with at most %s total digit.", 423 423 "Please enter a valid decimal number with at most %s total digits.", self.max_digits) % self.max_digits 424 424 if (not '.' in data and len(data) > (max_allowed_length - self.decimal_places - 1)) or ('.' in data and len(data) > (max_allowed_length - (self.decimal_places - len(data.split('.')[1])))): 425 raise ValidationError, ngettext( "Please enter a valid decimal number with a whole part of at most %s digit.",425 raise ValidationError, ungettext( "Please enter a valid decimal number with a whole part of at most %s digit.", 426 426 "Please enter a valid decimal number with a whole part of at most %s digits.", str(self.max_digits-self.decimal_places)) % str(self.max_digits-self.decimal_places) 427 427 if '.' in data and len(data.split('.')[1]) > self.decimal_places: 428 raise ValidationError, ngettext("Please enter a valid decimal number with at most %s decimal place.",428 raise ValidationError, ungettext("Please enter a valid decimal number with at most %s decimal place.", 429 429 "Please enter a valid decimal number with at most %s decimal places.", self.decimal_places) % self.decimal_places 430 430 431 431 class HasAllowableSize(object): … … 435 435 """ 436 436 def __init__(self, min_size=None, max_size=None, min_error_message=None, max_error_message=None): 437 437 self.min_size, self.max_size = min_size, max_size 438 self.min_error_message = min_error_message or lazy_inter( gettext_lazy("Make sure your uploaded file is at least %s bytes big."), min_size)439 self.max_error_message = max_error_message or lazy_inter( gettext_lazy("Make sure your uploaded file is at most %s bytes big."), max_size)438 self.min_error_message = min_error_message or lazy_inter(ugettext_lazy("Make sure your uploaded file is at least %s bytes big."), min_size) 439 self.max_error_message = max_error_message or lazy_inter(ugettext_lazy("Make sure your uploaded file is at most %s bytes big."), max_size) 440 440 441 441 def __call__(self, field_data, all_data): 442 442 try: 443 443 content = field_data['content'] 444 444 except TypeError: 445 raise ValidationError, gettext_lazy("No file was submitted. Check the encoding type on the form.")445 raise ValidationError, ugettext_lazy("No file was submitted. Check the encoding type on the form.") 446 446 if self.min_size is not None and len(content) < self.min_size: 447 447 raise ValidationError, self.min_error_message 448 448 if self.max_size is not None and len(content) > self.max_size: … … 453 453 Checks that the field matches the given regular-expression. The regex 454 454 should be in string format, not already compiled. 455 455 """ 456 def __init__(self, regexp, error_message= gettext_lazy("The format for this field is wrong.")):456 def __init__(self, regexp, error_message=ugettext_lazy("The format for this field is wrong.")): 457 457 self.regexp = re.compile(regexp) 458 458 self.error_message = error_message 459 459 … … 468 468 as a validation error. The message is rather unspecific, so it's best to 469 469 specify one on instantiation. 470 470 """ 471 def __init__(self, validator_list=None, error_message= gettext_lazy("This field is invalid.")):471 def __init__(self, validator_list=None, error_message=ugettext_lazy("This field is invalid.")): 472 472 if validator_list is None: validator_list = [] 473 473 self.validator_list = validator_list 474 474 self.error_message = error_message … … 504 504 try: 505 505 info = urllib2.urlopen(field_data).info() 506 506 except (urllib2.HTTPError, urllib2.URLError): 507 raise URLMimeTypeCheck.CouldNotRetrieve, gettext("Could not retrieve anything from %s.") % field_data507 raise URLMimeTypeCheck.CouldNotRetrieve, ugettext("Could not retrieve anything from %s.") % field_data 508 508 content_type = info['content-type'] 509 509 if content_type not in self.mime_type_list: 510 raise URLMimeTypeCheck.InvalidContentType, gettext("The URL %(url)s returned the invalid Content-Type header '%(contenttype)s'.") % {510 raise URLMimeTypeCheck.InvalidContentType, ugettext("The URL %(url)s returned the invalid Content-Type header '%(contenttype)s'.") % { 511 511 'url': field_data, 'contenttype': content_type} 512 512 513 513 class RelaxNGCompact(object): -
django/templatetags/i18n.py
40 40 if self.noop: 41 41 return value 42 42 else: 43 return translation. gettext(value)43 return translation.ugettext(value) 44 44 45 45 class BlockTranslateNode(Node): 46 46 def __init__(self, extra_context, singular, plural=None, countervar=None, counter=None): … … 68 68 count = self.counter.resolve(context) 69 69 context[self.countervar] = count 70 70 plural = self.render_token_list(self.plural) 71 result = translation. ngettext(singular, plural, count) % context71 result = translation.ungettext(singular, plural, count) % context 72 72 else: 73 result = translation. gettext(singular) % context73 result = translation.ugettext(singular) % context 74 74 context.pop() 75 75 return result 76 76 -
django/newforms/fields.py
2 2 Field classes 3 3 """ 4 4 5 from django.utils.translation import gettext5 from django.utils.translation import ugettext 6 6 from django.utils.encoding import smart_unicode 7 7 from util import ErrorList, ValidationError 8 8 from widgets import TextInput, PasswordInput, HiddenInput, MultipleHiddenInput, CheckboxInput, Select, NullBooleanSelect, SelectMultiple … … 77 77 Raises ValidationError for any errors. 78 78 """ 79 79 if self.required and value in EMPTY_VALUES: 80 raise ValidationError( gettext(u'This field is required.'))80 raise ValidationError(ugettext(u'This field is required.')) 81 81 return value 82 82 83 83 def widget_attrs(self, widget): … … 100 100 return u'' 101 101 value = smart_unicode(value) 102 102 if self.max_length is not None and len(value) > self.max_length: 103 raise ValidationError( gettext(u'Ensure this value has at most %d characters.') % self.max_length)103 raise ValidationError(ugettext(u'Ensure this value has at most %d characters.') % self.max_length) 104 104 if self.min_length is not None and len(value) < self.min_length: 105 raise ValidationError( gettext(u'Ensure this value has at least %d characters.') % self.min_length)105 raise ValidationError(ugettext(u'Ensure this value has at least %d characters.') % self.min_length) 106 106 return value 107 107 108 108 def widget_attrs(self, widget): … … 125 125 try: 126 126 value = int(value) 127 127 except (ValueError, TypeError): 128 raise ValidationError( gettext(u'Enter a whole number.'))128 raise ValidationError(ugettext(u'Enter a whole number.')) 129 129 if self.max_value is not None and value > self.max_value: 130 raise ValidationError( gettext(u'Ensure this value is less than or equal to %s.') % self.max_value)130 raise ValidationError(ugettext(u'Ensure this value is less than or equal to %s.') % self.max_value) 131 131 if self.min_value is not None and value < self.min_value: 132 raise ValidationError( gettext(u'Ensure this value is greater than or equal to %s.') % self.min_value)132 raise ValidationError(ugettext(u'Ensure this value is greater than or equal to %s.') % self.min_value) 133 133 return value 134 134 135 135 DEFAULT_DATE_INPUT_FORMATS = ( … … 162 162 return datetime.date(*time.strptime(value, format)[:3]) 163 163 except ValueError: 164 164 continue 165 raise ValidationError( gettext(u'Enter a valid date.'))165 raise ValidationError(ugettext(u'Enter a valid date.')) 166 166 167 167 DEFAULT_TIME_INPUT_FORMATS = ( 168 168 '%H:%M:%S', # '14:30:59' … … 189 189 return datetime.time(*time.strptime(value, format)[3:6]) 190 190 except ValueError: 191 191 continue 192 raise ValidationError( gettext(u'Enter a valid time.'))192 raise ValidationError(ugettext(u'Enter a valid time.')) 193 193 194 194 DEFAULT_DATETIME_INPUT_FORMATS = ( 195 195 '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' … … 225 225 return datetime.datetime(*time.strptime(value, format)[:6]) 226 226 except ValueError: 227 227 continue 228 raise ValidationError( gettext(u'Enter a valid date/time.'))228 raise ValidationError(ugettext(u'Enter a valid date/time.')) 229 229 230 230 class RegexField(Field): 231 231 def __init__(self, regex, max_length=None, min_length=None, error_message=None, *args, **kwargs): … … 239 239 regex = re.compile(regex) 240 240 self.regex = regex 241 241 self.max_length, self.min_length = max_length, min_length 242 self.error_message = error_message or gettext(u'Enter a valid value.')242 self.error_message = error_message or ugettext(u'Enter a valid value.') 243 243 244 244 def clean(self, value): 245 245 """ … … 253 253 if value == u'': 254 254 return value 255 255 if self.max_length is not None and len(value) > self.max_length: 256 raise ValidationError( gettext(u'Ensure this value has at most %d characters.') % self.max_length)256 raise ValidationError(ugettext(u'Ensure this value has at most %d characters.') % self.max_length) 257 257 if self.min_length is not None and len(value) < self.min_length: 258 raise ValidationError( gettext(u'Ensure this value has at least %d characters.') % self.min_length)258 raise ValidationError(ugettext(u'Ensure this value has at least %d characters.') % self.min_length) 259 259 if not self.regex.search(value): 260 260 raise ValidationError(self.error_message) 261 261 return value … … 268 268 class EmailField(RegexField): 269 269 def __init__(self, max_length=None, min_length=None, *args, **kwargs): 270 270 RegexField.__init__(self, email_re, max_length, min_length, 271 gettext(u'Enter a valid e-mail address.'), *args, **kwargs)271 ugettext(u'Enter a valid e-mail address.'), *args, **kwargs) 272 272 273 273 url_re = re.compile( 274 274 r'^https?://' # http:// or https:// … … 286 286 class URLField(RegexField): 287 287 def __init__(self, max_length=None, min_length=None, verify_exists=False, 288 288 validator_user_agent=URL_VALIDATOR_USER_AGENT, *args, **kwargs): 289 super(URLField, self).__init__(url_re, max_length, min_length, gettext(u'Enter a valid URL.'), *args, **kwargs)289 super(URLField, self).__init__(url_re, max_length, min_length, ugettext(u'Enter a valid URL.'), *args, **kwargs) 290 290 self.verify_exists = verify_exists 291 291 self.user_agent = validator_user_agent 292 292 … … 308 308 req = urllib2.Request(value, None, headers) 309 309 u = urllib2.urlopen(req) 310 310 except ValueError: 311 raise ValidationError( gettext(u'Enter a valid URL.'))311 raise ValidationError(ugettext(u'Enter a valid URL.')) 312 312 except: # urllib2.URLError, httplib.InvalidURL, etc. 313 raise ValidationError( gettext(u'This URL appears to be a broken link.'))313 raise ValidationError(ugettext(u'This URL appears to be a broken link.')) 314 314 return value 315 315 316 316 class BooleanField(Field): … … 361 361 return value 362 362 valid_values = set([str(k) for k, v in self.choices]) 363 363 if value not in valid_values: 364 raise ValidationError( gettext(u'Select a valid choice. That choice is not one of the available choices.'))364 raise ValidationError(ugettext(u'Select a valid choice. That choice is not one of the available choices.')) 365 365 return value 366 366 367 367 class MultipleChoiceField(ChoiceField): … … 373 373 Validates that the input is a list or tuple. 374 374 """ 375 375 if self.required and not value: 376 raise ValidationError( gettext(u'This field is required.'))376 raise ValidationError(ugettext(u'This field is required.')) 377 377 elif not self.required and not value: 378 378 return [] 379 379 if not isinstance(value, (list, tuple)): 380 raise ValidationError( gettext(u'Enter a list of values.'))380 raise ValidationError(ugettext(u'Enter a list of values.')) 381 381 new_value = [] 382 382 for val in value: 383 383 val = smart_unicode(val) … … 386 386 valid_values = set([smart_unicode(k) for k, v in self.choices]) 387 387 for val in new_value: 388 388 if val not in valid_values: 389 raise ValidationError( gettext(u'Select a valid choice. %s is not one of the available choices.') % val)389 raise ValidationError(ugettext(u'Select a valid choice. %s is not one of the available choices.') % val) 390 390 return new_value 391 391 392 392 class ComboField(Field): … … 449 449 clean_data = [] 450 450 errors = ErrorList() 451 451 if self.required and not value: 452 raise ValidationError( gettext(u'This field is required.'))452 raise ValidationError(ugettext(u'This field is required.')) 453 453 elif not self.required and not value: 454 454 return self.compress([]) 455 455 if not isinstance(value, (list, tuple)): 456 raise ValidationError( gettext(u'Enter a list of values.'))456 raise ValidationError(ugettext(u'Enter a list of values.')) 457 457 for i, field in enumerate(self.fields): 458 458 try: 459 459 field_value = value[i] 460 460 except KeyError: 461 461 field_value = None 462 462 if self.required and field_value in EMPTY_VALUES: 463 raise ValidationError( gettext(u'This field is required.'))463 raise ValidationError(ugettext(u'This field is required.')) 464 464 try: 465 465 clean_data.append(field.clean(field_value)) 466 466 except ValidationError, e: -
tests/modeltests/validation/models.py
42 42 43 43 >>> p = Person(**dict(valid_params, id='foo')) 44 44 >>> p.validate() 45 {'id': [ 'This value must be an integer.']}45 {'id': [u'This value must be an integer.']} 46 46 47 47 >>> p = Person(**dict(valid_params, id=None)) 48 48 >>> p.validate() … … 76 76 77 77 >>> p = Person(**dict(valid_params, is_child='foo')) 78 78 >>> p.validate() 79 {'is_child': [ 'This value must be either True or False.']}79 {'is_child': [u'This value must be either True or False.']} 80 80 81 81 >>> p = Person(**dict(valid_params, name=u'Jose')) 82 82 >>> p.validate() … … 116 116 117 117 >>> p = Person(**dict(valid_params, birthdate='foo')) 118 118 >>> p.validate() 119 {'birthdate': [ 'Enter a valid date in YYYY-MM-DD format.']}119 {'birthdate': [u'Enter a valid date in YYYY-MM-DD format.']} 120 120 121 121 >>> p = Person(**dict(valid_params, favorite_moment=datetime.datetime(2002, 4, 3, 13, 23))) 122 122 >>> p.validate() … … 144 144 145 145 >>> p = Person(**dict(valid_params, email=22)) 146 146 >>> p.validate() 147 {'email': [ 'Enter a valid e-mail address.']}147 {'email': [u'Enter a valid e-mail address.']} 148 148 149 149 # Make sure that Date and DateTime return validation errors and don't raise Python errors. 150 150 >>> Person(name='John Doe', is_child=True, email='abc@def.com').validate() 151 {'favorite_moment': [ 'This field is required.'], 'birthdate': ['This field is required.']}151 {'favorite_moment': [u'This field is required.'], 'birthdate': [u'This field is required.']} 152 152 153 153 """} -
tests/modeltests/manipulators/models.py
41 41 42 42 # Attempt to add a Musician without a first_name. 43 43 >>> man.get_validation_errors(MultiValueDict({'last_name': ['Blakey']})) 44 {'first_name': [ 'This field is required.']}44 {'first_name': [u'This field is required.']} 45 45 46 46 # Attempt to add a Musician without a first_name and last_name. 47 47 >>> man.get_validation_errors(MultiValueDict({})) 48 {'first_name': [ 'This field is required.'], 'last_name': ['This field is required.']}48 {'first_name': [u'This field is required.'], 'last_name': [u'This field is required.']} 49 49 50 50 # Attempt to create an Album without a name or musician. 51 51 >>> man = Album.AddManipulator() 52 52 >>> man.get_validation_errors(MultiValueDict({})) 53 {'musician': [ 'This field is required.'], 'name': ['This field is required.']}53 {'musician': [u'This field is required.'], 'name': [u'This field is required.']} 54 54 55 55 # Attempt to create an Album with an invalid musician. 56 56 >>> man.get_validation_errors(MultiValueDict({'name': ['Sallies Fforth'], 'musician': ['foo']})) 57 {'musician': [ "Select a valid choice; 'foo' is not in ['', '1']."]}57 {'musician': [u"Select a valid choice; 'foo' is not in ['', '1']."]} 58 58 59 59 # Attempt to create an Album with an invalid release_date. 60 60 >>> man.get_validation_errors(MultiValueDict({'name': ['Sallies Fforth'], 'musician': ['1'], 'release_date': 'today'})) 61 {'release_date': [ 'Enter a valid date in YYYY-MM-DD format.']}61 {'release_date': [u'Enter a valid date in YYYY-MM-DD format.']} 62 62 63 63 # Create an Album without a release_date (because it's optional). 64 64 >>> data = MultiValueDict({'name': ['Ella and Basie'], 'musician': ['1']})