Ticket #4152: 4152.2.cumulative.diff

File 4152.2.cumulative.diff, 44.6 KB (added by Ivan Sagalaev <Maniac@…>, 17 years ago)

Cumulative patch including oldforms and core.validators

  • django/oldforms/__init__.py

     
    22from django.core.exceptions import PermissionDenied
    33from django.utils.html import escape
    44from django.conf import settings
    5 from django.utils.translation import gettext, ngettext
     5from django.utils.translation import ugettext, ungettext
    66
    77FORM_FIELD_ID_PREFIX = 'id_'
    88
     
    6666                    errors.setdefault(field.field_name, []).extend(e.messages)
    6767
    6868#            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.'))
    7070#                continue
    7171#            try:
    7272#                validator_list = field.validator_list
     
    354354    def get_validation_errors(self, new_data):
    355355        errors = {}
    356356        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.'))
    358358            return errors
    359359        try:
    360360            for validator in self.validator_list:
     
    389389
    390390    def isValidLength(self, data, form):
    391391        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.",
    393393                "Ensure your text is less than %s characters.", self.maxlength) % self.maxlength
    394394
    395395    def hasNoNewlines(self, data, form):
    396396        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.")
    398398
    399399    def render(self, data):
    400400        if data is None:
     
    495495        str_data = str(data)
    496496        str_choices = [str(item[0]) for item in self.choices]
    497497        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}
    499499
    500500class NullSelectField(SelectField):
    501501    "This SelectField converts blank fields to None"
     
    568568        str_data = str(data)
    569569        str_choices = [str(item[0]) for item in self.choices]
    570570        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}
    572572
    573573class NullBooleanField(SelectField):
    574574    "This SelectField provides 'Yes', 'No' and 'Unknown', mapping results to True, False or None"
     
    607607        str_choices = [str(item[0]) for item in self.choices]
    608608        for val in map(str, field_data):
    609609            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}
    611611
    612612    def html2python(data):
    613613        if data is None:
     
    669669        try:
    670670            content = field_data['content']
    671671        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.")
    673673        if not content:
    674             raise validators.CriticalValidationError, gettext("The submitted file is empty.")
     674            raise validators.CriticalValidationError, ugettext("The submitted file is empty.")
    675675
    676676    def render(self, data):
    677677        return '<input type="file" id="%s" class="v%s" name="%s" />' % \
     
    727727
    728728    def isSmallInteger(self, field_data, all_data):
    729729        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.")
    731731
    732732class PositiveIntegerField(IntegerField):
    733733    def __init__(self, field_name, length=10, maxlength=None, is_required=False, validator_list=None):
     
    737737
    738738    def isPositive(self, field_data, all_data):
    739739        if int(field_data) < 0:
    740             raise validators.CriticalValidationError, gettext("Enter a positive number.")
     740            raise validators.CriticalValidationError, ugettext("Enter a positive number.")
    741741
    742742class PositiveSmallIntegerField(IntegerField):
    743743    def __init__(self, field_name, length=5, maxlength=None, is_required=False, validator_list=None):
     
    747747
    748748    def isPositiveSmall(self, field_data, all_data):
    749749        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.")
    751751
    752752class FloatField(TextField):
    753753    def __init__(self, field_name, max_digits, decimal_places, is_required=False, validator_list=None):
  • django/db/models/fields/__init__.py

     
    88from django.utils.functional import curry
    99from django.utils.itercompat import tee
    1010from django.utils.text import capfirst
    11 from django.utils.translation import gettext, gettext_lazy
     11from django.utils.translation import ugettext, ugettext_lazy
    1212import datetime, os, time
    1313
    1414class NOT_PROVIDED:
     
    3939        return
    4040    if getattr(self, 'original_object', None) and self.original_object._get_pk_val() == old_obj._get_pk_val():
    4141        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}
    4343
    4444# A guide to Field parameters:
    4545#
     
    114114        Subclasses should implement validate(), not validate_full().
    115115        """
    116116        if not self.blank and not field_data:
    117             return [gettext_lazy('This field is required.')]
     117            return [ugettext_lazy('This field is required.')]
    118118        try:
    119119            self.validate(field_data, all_data)
    120120        except validators.ValidationError, e:
     
    271271                    core_field_names.extend(f.get_manipulator_field_names(name_prefix))
    272272            # Now, if there are any, add the validator to this FormField.
    273273            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.")))
    275275
    276276        # Finally, add the field_names.
    277277        field_names = self.get_manipulator_field_names(name_prefix)
     
    364364        try:
    365365            return int(value)
    366366        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.")
    368368
    369369    def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True):
    370370        if not rel:
     
    399399        if value in (True, False): return value
    400400        if value in ('t', 'True', '1'): return True
    401401        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.")
    403403
    404404    def get_manipulator_field_objs(self):
    405405        return [oldforms.CheckboxField]
     
    420420            if self.null:
    421421                return value
    422422            else:
    423                 raise validators.ValidationError, gettext_lazy("This field cannot be null.")
     423                raise validators.ValidationError, ugettext_lazy("This field cannot be null.")
    424424        return str(value)
    425425
    426426    def formfield(self, **kwargs):
     
    454454        try:
    455455            return datetime.date(*time.strptime(value, '%Y-%m-%d')[:3])
    456456        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.')
    458458
    459459    def get_db_prep_lookup(self, lookup_type, value):
    460460        if lookup_type == 'range':
     
    523523                try:
    524524                    return datetime.datetime(*time.strptime(value, '%Y-%m-%d')[:3])
    525525                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.')
    527527
    528528    def get_db_prep_save(self, value):
    529529        # Casts dates into string format for entry into database.
     
    607607                        self.always_test = True
    608608                    def __call__(self, field_data, all_data):
    609609                        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."))
    611611                            c(field_data, all_data)
    612612                # First, get the core fields, if any.
    613613                core_field_names = []
     
    618618                if core_field_names:
    619619                    field_list[0].validator_list.append(RequiredFileField(core_field_names, field_list[1].field_name))
    620620            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."))
    622622                v.always_test = True
    623623                field_list[0].validator_list.append(v)
    624624                field_list[0].is_required = field_list[1].is_required = False
     
    748748        if value in ('None'): return None
    749749        if value in ('t', 'True', '1'): return True
    750750        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.")
    752752
    753753    def get_manipulator_field_objs(self):
    754754        return [oldforms.NullBooleanField]
  • django/core/validators.py

     
    1010
    1111import urllib2
    1212from django.conf import settings
    13 from django.utils.translation import gettext, gettext_lazy, ngettext
     13from django.utils.translation import ugettext, ugettext_lazy, ungettext
    1414from django.utils.functional import Promise, lazy
    1515import re
    1616
     
    6161
    6262def isAlphaNumeric(field_data, all_data):
    6363    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.")
    6565
    6666def isAlphaNumericURL(field_data, all_data):
    6767    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.")
    6969
    7070def isSlug(field_data, all_data):
    7171    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.")
    7373
    7474def isLowerCase(field_data, all_data):
    7575    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.")
    7777
    7878def isUpperCase(field_data, all_data):
    7979    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.")
    8181
    8282def isCommaSeparatedIntegerList(field_data, all_data):
    8383    for supposed_int in field_data.split(','):
    8484        try:
    8585            int(supposed_int)
    8686        except ValueError:
    87             raise ValidationError, gettext("Enter only digits separated by commas.")
     87            raise ValidationError, ugettext("Enter only digits separated by commas.")
    8888
    8989def isCommaSeparatedEmailList(field_data, all_data):
    9090    """
     
    9696        try:
    9797            isValidEmail(supposed_email.strip(), '')
    9898        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.")
    100100
    101101def isValidIPAddress4(field_data, all_data):
    102102    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.")
    104104
    105105def isNotEmpty(field_data, all_data):
    106106    if field_data.strip() == '':
    107         raise ValidationError, gettext("Empty values are not allowed here.")
     107        raise ValidationError, ugettext("Empty values are not allowed here.")
    108108
    109109def isOnlyDigits(field_data, all_data):
    110110    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.")
    112112
    113113def isNotOnlyDigits(field_data, all_data):
    114114    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.")
    116116
    117117def isInteger(field_data, all_data):
    118118    # This differs from isOnlyDigits because this accepts the negative sign
    119119    if not integer_re.search(field_data):
    120         raise ValidationError, gettext("Enter a whole number.")
     120        raise ValidationError, ugettext("Enter a whole number.")
    121121
    122122def isOnlyLetters(field_data, all_data):
    123123    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.")
    125125
    126126def _isValidDate(date_string):
    127127    """
     
    136136    # This check is needed because strftime is used when saving the date
    137137    # value to the database, and strftime requires that the year be >=1900.
    138138    if year < 1900:
    139         raise ValidationError, gettext('Year must be 1900 or later.')
     139        raise ValidationError, ugettext('Year must be 1900 or later.')
    140140    try:
    141141        date(year, month, day)
    142142    except ValueError, e:
    143         msg = gettext('Invalid date: %s') % gettext(str(e))
     143        msg = ugettext('Invalid date: %s') % ugettext(str(e))
    144144        raise ValidationError, msg   
    145145
    146146def isValidANSIDate(field_data, all_data):
    147147    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.')
    149149    _isValidDate(field_data)
    150150
    151151def isValidANSITime(field_data, all_data):
    152152    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.')
    154154
    155155def isValidANSIDatetime(field_data, all_data):
    156156    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.')
    158158    _isValidDate(field_data.split()[0])
    159159
    160160def isValidEmail(field_data, all_data):
    161161    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.')
    163163
    164164def isValidImage(field_data, all_data):
    165165    """
     
    171171    try:
    172172        content = field_data['content']
    173173    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.")
    175175    try:
    176176        Image.open(StringIO(content))
    177177    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.")
    179179
    180180def isValidImageURL(field_data, all_data):
    181181    uc = URLMimeTypeCheck(('image/jpeg', 'image/gif', 'image/png'))
    182182    try:
    183183        uc(field_data, all_data)
    184184    except URLMimeTypeCheck.InvalidContentType:
    185         raise ValidationError, gettext("The URL %s does not point to a valid image.") % field_data
     185        raise ValidationError, ugettext("The URL %s does not point to a valid image.") % field_data
    186186
    187187def isValidPhone(field_data, all_data):
    188188    if not phone_re.search(field_data):
    189         raise ValidationError, gettext('Phone numbers must be in XXX-XXX-XXXX format. "%s" is invalid.') % field_data
     189        raise ValidationError, ugettext('Phone numbers must be in XXX-XXX-XXXX format. "%s" is invalid.') % field_data
    190190
    191191def isValidQuicktimeVideoURL(field_data, all_data):
    192192    "Checks that the given URL is a video that can be played by QuickTime (qt, mpeg)"
     
    194194    try:
    195195        uc(field_data, all_data)
    196196    except URLMimeTypeCheck.InvalidContentType:
    197         raise ValidationError, gettext("The URL %s does not point to a valid QuickTime video.") % field_data
     197        raise ValidationError, ugettext("The URL %s does not point to a valid QuickTime video.") % field_data
    198198
    199199def isValidURL(field_data, all_data):
    200200    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.")
    202202
    203203def isValidHTML(field_data, all_data):
    204204    import urllib, urllib2
     
    212212        return
    213213    from xml.dom.minidom import parseString
    214214    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)
    216216
    217217def isWellFormedXml(field_data, all_data):
    218218    from xml.dom.minidom import parseString
    219219    try:
    220220        parseString(field_data)
    221221    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)
    223223
    224224def isWellFormedXmlFragment(field_data, all_data):
    225225    isWellFormedXml('<root>%s</root>' % field_data, all_data)
     
    249249    "Checks that the given string is a valid two-letter U.S. state abbreviation"
    250250    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']
    251251    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.")
    253253
    254254def hasNoProfanities(field_data, all_data):
    255255    """
     
    263263    if words_seen:
    264264        from django.utils.text import get_text_list
    265265        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.",
    267267            "Watch your mouth! The words %s are not allowed here.", plural) % \
    268268            get_text_list(['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in words_seen], 'and')
    269269
    270270class AlwaysMatchesOtherField(object):
    271271    def __init__(self, other_field_name, error_message=None):
    272272        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)
    274274        self.always_test = True
    275275
    276276    def __call__(self, field_data, all_data):
     
    289289                v(field_data, all_data)
    290290
    291291class 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.")):
    293293        self.other, self.error_message = other_field_name, error_message
    294294        self.always_test = True
    295295
     
    298298            raise ValidationError, self.error_message
    299299
    300300class 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.")):
    302302        self.other, self.error_message = other_field_names, error_message
    303303        self.always_test = True
    304304
     
    309309
    310310class RequiredIfOtherFieldGiven(RequiredIfOtherFieldsGiven):
    311311    "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.")):
    313313        RequiredIfOtherFieldsGiven.__init__(self, [other_field_name], error_message)
    314314
    315315class RequiredIfOtherFieldEquals(object):
     
    317317        self.other_field = other_field
    318318        self.other_value = other_value
    319319        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"), {
    321321            'field': other_field, 'value': other_label})
    322322        self.always_test = True
    323323
     
    330330        self.other_field = other_field
    331331        self.other_value = other_value
    332332        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"), {
    334334            'field': other_field, 'value': other_label})
    335335        self.always_test = True
    336336
     
    349349class UniqueAmongstFieldsWithPrefix(object):
    350350    def __init__(self, field_name, prefix, error_message):
    351351        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.")
    353353
    354354    def __call__(self, field_data, all_data):
    355355        for field_name, value in all_data.items():
     
    364364        self.lower, self.upper = lower, upper
    365365        if not error_message:
    366366            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}
    368368            elif lower:
    369                 self.error_message = gettext("This value must be at least %s.") % lower
     369                self.error_message = ugettext("This value must be at least %s.") % lower
    370370            elif upper:
    371                 self.error_message = gettext("This value must be no more than %s.") % upper
     371                self.error_message = ugettext("This value must be no more than %s.") % upper
    372372        else:
    373373            self.error_message = error_message
    374374
     
    404404        from math import log
    405405        val = log(int(field_data)) / log(self.power_of)
    406406        if val != int(val):
    407             raise ValidationError, gettext("This value must be a power of %s.") % self.power_of
     407            raise ValidationError, ugettext("This value must be a power of %s.") % self.power_of
    408408
    409409class IsValidFloat(object):
    410410    def __init__(self, max_digits, decimal_places):
     
    415415        try:
    416416            float(data)
    417417        except ValueError:
    418             raise ValidationError, gettext("Please enter a valid decimal number.")
     418            raise ValidationError, ugettext("Please enter a valid decimal number.")
    419419        # Negative floats require more space to input.
    420420        max_allowed_length = data.startswith('-') and (self.max_digits + 2) or (self.max_digits + 1)
    421421        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.",
    423423                "Please enter a valid decimal number with at most %s total digits.", self.max_digits) % self.max_digits
    424424        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.",
    426426                "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)
    427427        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.",
    429429                "Please enter a valid decimal number with at most %s decimal places.", self.decimal_places) % self.decimal_places
    430430
    431431class HasAllowableSize(object):
     
    435435    """
    436436    def __init__(self, min_size=None, max_size=None, min_error_message=None, max_error_message=None):
    437437        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)
    440440
    441441    def __call__(self, field_data, all_data):
    442442        try:
    443443            content = field_data['content']
    444444        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.")
    446446        if self.min_size is not None and len(content) < self.min_size:
    447447            raise ValidationError, self.min_error_message
    448448        if self.max_size is not None and len(content) > self.max_size:
     
    453453    Checks that the field matches the given regular-expression. The regex
    454454    should be in string format, not already compiled.
    455455    """
    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.")):
    457457        self.regexp = re.compile(regexp)
    458458        self.error_message = error_message
    459459
     
    468468    as a validation error. The message is rather unspecific, so it's best to
    469469    specify one on instantiation.
    470470    """
    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.")):
    472472        if validator_list is None: validator_list = []
    473473        self.validator_list = validator_list
    474474        self.error_message = error_message
     
    504504        try:
    505505            info = urllib2.urlopen(field_data).info()
    506506        except (urllib2.HTTPError, urllib2.URLError):
    507             raise URLMimeTypeCheck.CouldNotRetrieve, gettext("Could not retrieve anything from %s.") % field_data
     507            raise URLMimeTypeCheck.CouldNotRetrieve, ugettext("Could not retrieve anything from %s.") % field_data
    508508        content_type = info['content-type']
    509509        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'.") % {
    511511                'url': field_data, 'contenttype': content_type}
    512512
    513513class RelaxNGCompact(object):
  • django/templatetags/i18n.py

     
    4040        if self.noop:
    4141            return value
    4242        else:
    43             return translation.gettext(value)
     43            return translation.ugettext(value)
    4444
    4545class BlockTranslateNode(Node):
    4646    def __init__(self, extra_context, singular, plural=None, countervar=None, counter=None):
     
    6868            count = self.counter.resolve(context)
    6969            context[self.countervar] = count
    7070            plural = self.render_token_list(self.plural)
    71             result = translation.ngettext(singular, plural, count) % context
     71            result = translation.ungettext(singular, plural, count) % context
    7272        else:
    73             result = translation.gettext(singular) % context
     73            result = translation.ugettext(singular) % context
    7474        context.pop()
    7575        return result
    7676
  • django/newforms/fields.py

     
    22Field classes
    33"""
    44
    5 from django.utils.translation import gettext
     5from django.utils.translation import ugettext
    66from django.utils.encoding import smart_unicode
    77from util import ErrorList, ValidationError
    88from widgets import TextInput, PasswordInput, HiddenInput, MultipleHiddenInput, CheckboxInput, Select, NullBooleanSelect, SelectMultiple
     
    7777        Raises ValidationError for any errors.
    7878        """
    7979        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.'))
    8181        return value
    8282
    8383    def widget_attrs(self, widget):
     
    100100            return u''
    101101        value = smart_unicode(value)
    102102        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)
    104104        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)
    106106        return value
    107107
    108108    def widget_attrs(self, widget):
     
    125125        try:
    126126            value = int(value)
    127127        except (ValueError, TypeError):
    128             raise ValidationError(gettext(u'Enter a whole number.'))
     128            raise ValidationError(ugettext(u'Enter a whole number.'))
    129129        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)
    131131        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)
    133133        return value
    134134
    135135DEFAULT_DATE_INPUT_FORMATS = (
     
    162162                return datetime.date(*time.strptime(value, format)[:3])
    163163            except ValueError:
    164164                continue
    165         raise ValidationError(gettext(u'Enter a valid date.'))
     165        raise ValidationError(ugettext(u'Enter a valid date.'))
    166166
    167167DEFAULT_TIME_INPUT_FORMATS = (
    168168    '%H:%M:%S',     # '14:30:59'
     
    189189                return datetime.time(*time.strptime(value, format)[3:6])
    190190            except ValueError:
    191191                continue
    192         raise ValidationError(gettext(u'Enter a valid time.'))
     192        raise ValidationError(ugettext(u'Enter a valid time.'))
    193193
    194194DEFAULT_DATETIME_INPUT_FORMATS = (
    195195    '%Y-%m-%d %H:%M:%S',     # '2006-10-25 14:30:59'
     
    225225                return datetime.datetime(*time.strptime(value, format)[:6])
    226226            except ValueError:
    227227                continue
    228         raise ValidationError(gettext(u'Enter a valid date/time.'))
     228        raise ValidationError(ugettext(u'Enter a valid date/time.'))
    229229
    230230class RegexField(Field):
    231231    def __init__(self, regex, max_length=None, min_length=None, error_message=None, *args, **kwargs):
     
    239239            regex = re.compile(regex)
    240240        self.regex = regex
    241241        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.')
    243243
    244244    def clean(self, value):
    245245        """
     
    253253        if value == u'':
    254254            return value
    255255        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)
    257257        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)
    259259        if not self.regex.search(value):
    260260            raise ValidationError(self.error_message)
    261261        return value
     
    268268class EmailField(RegexField):
    269269    def __init__(self, max_length=None, min_length=None, *args, **kwargs):
    270270        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)
    272272
    273273url_re = re.compile(
    274274    r'^https?://' # http:// or https://
     
    286286class URLField(RegexField):
    287287    def __init__(self, max_length=None, min_length=None, verify_exists=False,
    288288            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)
    290290        self.verify_exists = verify_exists
    291291        self.user_agent = validator_user_agent
    292292
     
    308308                req = urllib2.Request(value, None, headers)
    309309                u = urllib2.urlopen(req)
    310310            except ValueError:
    311                 raise ValidationError(gettext(u'Enter a valid URL.'))
     311                raise ValidationError(ugettext(u'Enter a valid URL.'))
    312312            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.'))
    314314        return value
    315315
    316316class BooleanField(Field):
     
    361361            return value
    362362        valid_values = set([str(k) for k, v in self.choices])
    363363        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.'))
    365365        return value
    366366
    367367class MultipleChoiceField(ChoiceField):
     
    373373        Validates that the input is a list or tuple.
    374374        """
    375375        if self.required and not value:
    376             raise ValidationError(gettext(u'This field is required.'))
     376            raise ValidationError(ugettext(u'This field is required.'))
    377377        elif not self.required and not value:
    378378            return []
    379379        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.'))
    381381        new_value = []
    382382        for val in value:
    383383            val = smart_unicode(val)
     
    386386        valid_values = set([smart_unicode(k) for k, v in self.choices])
    387387        for val in new_value:
    388388            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)
    390390        return new_value
    391391
    392392class ComboField(Field):
     
    449449        clean_data = []
    450450        errors = ErrorList()
    451451        if self.required and not value:
    452             raise ValidationError(gettext(u'This field is required.'))
     452            raise ValidationError(ugettext(u'This field is required.'))
    453453        elif not self.required and not value:
    454454            return self.compress([])
    455455        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.'))
    457457        for i, field in enumerate(self.fields):
    458458            try:
    459459                field_value = value[i]
    460460            except KeyError:
    461461                field_value = None
    462462            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.'))
    464464            try:
    465465                clean_data.append(field.clean(field_value))
    466466            except ValidationError, e:
  • tests/modeltests/validation/models.py

     
    4242
    4343>>> p = Person(**dict(valid_params, id='foo'))
    4444>>> p.validate()
    45 {'id': ['This value must be an integer.']}
     45{'id': [u'This value must be an integer.']}
    4646
    4747>>> p = Person(**dict(valid_params, id=None))
    4848>>> p.validate()
     
    7676
    7777>>> p = Person(**dict(valid_params, is_child='foo'))
    7878>>> 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.']}
    8080
    8181>>> p = Person(**dict(valid_params, name=u'Jose'))
    8282>>> p.validate()
     
    116116
    117117>>> p = Person(**dict(valid_params, birthdate='foo'))
    118118>>> 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.']}
    120120
    121121>>> p = Person(**dict(valid_params, favorite_moment=datetime.datetime(2002, 4, 3, 13, 23)))
    122122>>> p.validate()
     
    144144
    145145>>> p = Person(**dict(valid_params, email=22))
    146146>>> p.validate()
    147 {'email': ['Enter a valid e-mail address.']}
     147{'email': [u'Enter a valid e-mail address.']}
    148148
    149149# Make sure that Date and DateTime return validation errors and don't raise Python errors.
    150150>>> 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.']}
    152152
    153153"""}
  • tests/modeltests/manipulators/models.py

     
    4141
    4242# Attempt to add a Musician without a first_name.
    4343>>> man.get_validation_errors(MultiValueDict({'last_name': ['Blakey']}))
    44 {'first_name': ['This field is required.']}
     44{'first_name': [u'This field is required.']}
    4545
    4646# Attempt to add a Musician without a first_name and last_name.
    4747>>> 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.']}
    4949
    5050# Attempt to create an Album without a name or musician.
    5151>>> man = Album.AddManipulator()
    5252>>> 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.']}
    5454
    5555# Attempt to create an Album with an invalid musician.
    5656>>> 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']."]}
    5858
    5959# Attempt to create an Album with an invalid release_date.
    6060>>> 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.']}
    6262
    6363# Create an Album without a release_date (because it's optional).
    6464>>> data = MultiValueDict({'name': ['Ella and Basie'], 'musician': ['1']})
Back to Top