Python django.utils.text.format_lazy() Examples
The following are 30
code examples of django.utils.text.format_lazy().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.utils.text
, or try the search function
.
Example #1
Source File: utils.py From bioforum with MIT License | 6 votes |
def prefix_validation_error(error, prefix, code, params): """ Prefix a validation error message while maintaining the existing validation data structure. """ if error.error_list == [error]: error_params = error.params or {} return ValidationError( # We can't simply concatenate messages since they might require # their associated parameters to be expressed correctly which # is not something `format_lazy` does. For example, proxied # ngettext calls require a count parameter and are converted # to an empty string if they are missing it. message=format_lazy( '{}{}', SimpleLazyObject(lambda: prefix % params), SimpleLazyObject(lambda: error.message % error_params), ), code=code, params=dict(error_params, **params), ) return ValidationError([ prefix_validation_error(e, prefix, code, params) for e in error.error_list ])
Example #2
Source File: test_text.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_format_lazy(self): self.assertEqual('django/test', format_lazy('{}/{}', 'django', lazystr('test'))) self.assertEqual('django/test', format_lazy('{0}/{1}', *('django', 'test'))) self.assertEqual('django/test', format_lazy('{a}/{b}', **{'a': 'django', 'b': 'test'})) self.assertEqual('django/test', format_lazy('{a[0]}/{a[1]}', a=('django', 'test'))) t = {} s = format_lazy('{0[a]}-{p[a]}', t, p=t) t['a'] = lazystr('django') self.assertEqual('django-django', s) t['a'] = 'update' self.assertEqual('update-update', s) # The format string can be lazy. (string comes from contrib.admin) s = format_lazy( gettext_lazy("Added {name} \"{object}\"."), name='article', object='My first try', ) with override('fr'): self.assertEqual('Ajout de article «\xa0My first try\xa0».', s)
Example #3
Source File: tables.py From manila-ui with Apache License 2.0 | 6 votes |
def allowed(self, request, share=None): usages = manila.tenant_absolute_limits(request) shares_allowed = (usages['maxTotalShares'] > usages['totalSharesUsed'] and usages['maxTotalShareGigabytes'] > usages['totalShareGigabytesUsed']) if not shares_allowed: if "disabled" not in self.classes: self.classes = [c for c in self.classes] + ['disabled'] self.verbose_name = format_lazy( '{verbose_name} {quota_exceeded}', verbose_name=self.verbose_name, quota_exceeded=_("(Quota exceeded)")) else: self.verbose_name = _("Create Share") classes = [c for c in self.classes if c != "disabled"] self.classes = classes return True
Example #4
Source File: test_text.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_format_lazy(self): self.assertEqual('django/test', format_lazy('{}/{}', 'django', lazystr('test'))) self.assertEqual('django/test', format_lazy('{0}/{1}', *('django', 'test'))) self.assertEqual('django/test', format_lazy('{a}/{b}', **{'a': 'django', 'b': 'test'})) self.assertEqual('django/test', format_lazy('{a[0]}/{a[1]}', a=('django', 'test'))) t = {} s = format_lazy('{0[a]}-{p[a]}', t, p=t) t['a'] = lazystr('django') self.assertEqual('django-django', s) t['a'] = 'update' self.assertEqual('update-update', s) # The format string can be lazy. (string comes from contrib.admin) s = format_lazy( gettext_lazy("Added {name} \"{object}\"."), name='article', object='My first try', ) with override('fr'): self.assertEqual('Ajout de article «\xa0My first try\xa0».', s)
Example #5
Source File: utils.py From python2017 with MIT License | 6 votes |
def prefix_validation_error(error, prefix, code, params): """ Prefix a validation error message while maintaining the existing validation data structure. """ if error.error_list == [error]: error_params = error.params or {} return ValidationError( # We can't simply concatenate messages since they might require # their associated parameters to be expressed correctly which # is not something `format_lazy` does. For example, proxied # ungettext calls require a count parameter and are converted # to an empty string if they are missing it. message=format_lazy( '{}{}', SimpleLazyObject(lambda: prefix % params), SimpleLazyObject(lambda: error.message % error_params), ), code=code, params=dict(error_params, **params), ) return ValidationError([ prefix_validation_error(e, prefix, code, params) for e in error.error_list ])
Example #6
Source File: utils.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def prefix_validation_error(error, prefix, code, params): """ Prefix a validation error message while maintaining the existing validation data structure. """ if error.error_list == [error]: error_params = error.params or {} return ValidationError( # We can't simply concatenate messages since they might require # their associated parameters to be expressed correctly which # is not something `format_lazy` does. For example, proxied # ngettext calls require a count parameter and are converted # to an empty string if they are missing it. message=format_lazy( '{} {}', SimpleLazyObject(lambda: prefix % params), SimpleLazyObject(lambda: error.message % error_params), ), code=code, params={**error_params, **params}, ) return ValidationError([ prefix_validation_error(e, prefix, code, params) for e in error.error_list ])
Example #7
Source File: options.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def formfield_for_manytomany(self, db_field, request, **kwargs): """ Get a form Field for a ManyToManyField. """ # If it uses an intermediary model that isn't auto created, don't show # a field in admin. if not db_field.remote_field.through._meta.auto_created: return None db = kwargs.get('using') autocomplete_fields = self.get_autocomplete_fields(request) if db_field.name in autocomplete_fields: kwargs['widget'] = AutocompleteSelectMultiple(db_field.remote_field, self.admin_site, using=db) elif db_field.name in self.raw_id_fields: kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.remote_field, self.admin_site, using=db) elif db_field.name in list(self.filter_vertical) + list(self.filter_horizontal): kwargs['widget'] = widgets.FilteredSelectMultiple( db_field.verbose_name, db_field.name in self.filter_vertical ) if 'queryset' not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs['queryset'] = queryset form_field = db_field.formfield(**kwargs) if (isinstance(form_field.widget, SelectMultiple) and not isinstance(form_field.widget, (CheckboxSelectMultiple, AutocompleteSelectMultiple))): msg = _('Hold down "Control", or "Command" on a Mac, to select more than one.') help_text = form_field.help_text form_field.help_text = format_lazy('{} {}', help_text, msg) if help_text else msg return form_field
Example #8
Source File: validators.py From pasportaservo with GNU Affero General Public License v3.0 | 6 votes |
def validate_not_too_many_caps(value): """ Tries to figure out whether the value has too many capitals. Maximum two capitals per word. """ authorized_begining = ("a", "de", "la", "mac", "mc") message = _("It seems there are too many uppercase letters. Please try with '{correct_value}'.") message = format_lazy(message, correct_value=title_with_particule(value)) words = split(value) if not any(words): pass # For non latin letters elif value == value.upper(): validate_not_all_caps(value) else: for word in words: nb_caps = sum(1 for char in word if char.isupper()) if nb_caps > 1: if any([word.lower().startswith(s) for s in authorized_begining]): # This should validate 'McCoy' if nb_caps > 2: raise ValidationError(message, code='caps') else: raise ValidationError(message, code='caps')
Example #9
Source File: views.py From pasportaservo with GNU Affero General Public License v3.0 | 6 votes |
def dispatch(self, request, *args, **kwargs): code_from_kwarg = {v: k for k, v in self.book_codes.items()} code_from_kwarg.update({None: False}) self.in_book_status = code_from_kwarg[kwargs['in_book']] if self.in_book_status and not request.user.has_perm(PERM_SUPERVISOR): return HttpResponseRedirect(format_lazy( "{supervisors_url}#{section_countries}", supervisors_url=reverse_lazy('supervisors'), section_countries=pgettext_lazy("URL", "countries-list"), )) return super().dispatch(request, *args, **kwargs)
Example #10
Source File: auth.py From pasportaservo with GNU Affero General Public License v3.0 | 6 votes |
def get_permission_denied_message(self, object, context_omitted=False): if not context_omitted: countries = [self.get_location(object)] if not countries[0]: countries = self.get_owner(object).owned_places.filter( deleted=False ).values_list('country', flat=True).distinct() elif not countries[0].name: countries = [] else: countries = None if not countries: return _("Only administrators can access this page") to_string = lambda item: str(Country(item).name) join_lazy = keep_lazy_text(lambda items: ", ".join(map(to_string, items))) return format_lazy(self.permission_denied_message, this_country=join_lazy(countries))
Example #11
Source File: locations.py From c3nav with Apache License 2.0 | 5 votes |
def subtitle(self): result = self.category.title if hasattr(self, 'locations'): return format_lazy(_('{category_title}, {num_locations}'), category_title=result, num_locations=(ungettext_lazy('%(num)d location', '%(num)d locations', 'num') % {'num': len(self.locations)})) return result
Example #12
Source File: options.py From python with Apache License 2.0 | 5 votes |
def formfield_for_manytomany(self, db_field, request, **kwargs): """ Get a form Field for a ManyToManyField. """ # If it uses an intermediary model that isn't auto created, don't show # a field in admin. if not db_field.remote_field.through._meta.auto_created: return None db = kwargs.get('using') if db_field.name in self.raw_id_fields: kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.remote_field, self.admin_site, using=db) elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)): kwargs['widget'] = widgets.FilteredSelectMultiple( db_field.verbose_name, db_field.name in self.filter_vertical ) if 'queryset' not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs['queryset'] = queryset form_field = db_field.formfield(**kwargs) if isinstance(form_field.widget, SelectMultiple) and not isinstance(form_field.widget, CheckboxSelectMultiple): msg = _('Hold down "Control", or "Command" on a Mac, to select more than one.') help_text = form_field.help_text form_field.help_text = format_lazy('{} {}', help_text, msg) if help_text else msg return form_field
Example #13
Source File: fields.py From c3nav with Apache License 2.0 | 5 votes |
def __get__(self, instance, cls=None): if instance is None: return self fallback_value = self.field.fallback_value if fallback_value is not None: fallback_value = format_lazy(fallback_value, model=instance._meta.verbose_name, pk=instance.pk) return lazy_get_i18n_value(getattr(instance, self.field.attname), fallback_language=self.field.fallback_language, fallback_any=self.field.fallback_any, fallback_value=fallback_value)
Example #14
Source File: space.py From c3nav with Apache License 2.0 | 5 votes |
def subtitle(self): base_subtitle = super().subtitle space = getattr(self, '_space_cache', None) if space is not None: level = getattr(space, '_level_cache', None) if level is not None: return format_lazy(_('{category}, {space}, {level}'), category=base_subtitle, space=space.title, level=level.title) return format_lazy(_('{category}, {space}'), category=base_subtitle, level=space.title) return base_subtitle
Example #15
Source File: level.py From c3nav with Apache License 2.0 | 5 votes |
def subtitle(self): base_subtitle = super().subtitle level = getattr(self, '_level_cache', None) if level is not None: return format_lazy(_('{category}, {level}'), category=base_subtitle, level=level.title) return base_subtitle
Example #16
Source File: options.py From bioforum with MIT License | 5 votes |
def formfield_for_manytomany(self, db_field, request, **kwargs): """ Get a form Field for a ManyToManyField. """ # If it uses an intermediary model that isn't auto created, don't show # a field in admin. if not db_field.remote_field.through._meta.auto_created: return None db = kwargs.get('using') autocomplete_fields = self.get_autocomplete_fields(request) if db_field.name in autocomplete_fields: kwargs['widget'] = AutocompleteSelectMultiple(db_field.remote_field, self.admin_site, using=db) elif db_field.name in self.raw_id_fields: kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.remote_field, self.admin_site, using=db) elif db_field.name in list(self.filter_vertical) + list(self.filter_horizontal): kwargs['widget'] = widgets.FilteredSelectMultiple( db_field.verbose_name, db_field.name in self.filter_vertical ) if 'queryset' not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs['queryset'] = queryset form_field = db_field.formfield(**kwargs) if (isinstance(form_field.widget, SelectMultiple) and not isinstance(form_field.widget, (CheckboxSelectMultiple, AutocompleteSelectMultiple))): msg = _('Hold down "Control", or "Command" on a Mac, to select more than one.') help_text = form_field.help_text form_field.help_text = format_lazy('{} {}', help_text, msg) if help_text else msg return form_field
Example #17
Source File: forms.py From c3nav with Apache License 2.0 | 5 votes |
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) new_fields = OrderedDict() self.i18n_fields = [] for name, form_field in self.fields.items(): model_field = self.instance._meta.get_field(name) if not isinstance(model_field, I18nField): new_fields[name] = form_field continue values = OrderedDict((lang_code, '') for lang_code, language in settings.LANGUAGES) if self.instance is not None and self.instance.pk: values.update(getattr(self.instance, model_field.attname)) has_values = False for language in values.keys(): sub_field_name = '%s__%s' % (name, language) new_value = self.data.get(sub_field_name) if new_value is not None: has_values = True values[language] = new_value language_info = get_language_info(language) field_title = format_lazy(_('{field_name} ({lang})'), field_name=capfirst(model_field.verbose_name), lang=language_info['name_translated']) new_fields[sub_field_name] = CharField(label=field_title, required=False, initial=values[language].strip(), max_length=model_field.i18n_max_length, help_text=form_field.help_text) if has_values: self.i18n_fields.append((model_field, values)) self.fields = new_fields
Example #18
Source File: options.py From python2017 with MIT License | 5 votes |
def formfield_for_manytomany(self, db_field, request, **kwargs): """ Get a form Field for a ManyToManyField. """ # If it uses an intermediary model that isn't auto created, don't show # a field in admin. if not db_field.remote_field.through._meta.auto_created: return None db = kwargs.get('using') if db_field.name in self.raw_id_fields: kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.remote_field, self.admin_site, using=db) elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)): kwargs['widget'] = widgets.FilteredSelectMultiple( db_field.verbose_name, db_field.name in self.filter_vertical ) if 'queryset' not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs['queryset'] = queryset form_field = db_field.formfield(**kwargs) if isinstance(form_field.widget, SelectMultiple) and not isinstance(form_field.widget, CheckboxSelectMultiple): msg = _('Hold down "Control", or "Command" on a Mac, to select more than one.') help_text = form_field.help_text form_field.help_text = format_lazy('{} {}', help_text, msg) if help_text else msg return form_field
Example #19
Source File: filters.py From oldp with MIT License | 5 votes |
def build_choices(self, fields, labels): # With lazy translate ascending = [ (param, labels.get(field, _(pretty_name(param)))) for field, param in fields.items() ] descending = [ ('-%s' % param, labels.get('-%s' % param, format_lazy('{} ({})', label, _('descending')))) for param, label in ascending ] # interleave the ascending and descending choices return [val for pair in zip(ascending, descending) for val in pair]
Example #20
Source File: views.py From pasportaservo with GNU Affero General Public License v3.0 | 5 votes |
def get(self, request, *args, **kwargs): try: return HttpResponseRedirect(format_lazy( "{settings_url}#{section_email}", settings_url=reverse_lazy('profile_settings', kwargs={ 'pk': request.user.profile.pk, 'slug': request.user.profile.autoslug}), section_email=pgettext_lazy("URL", "email-addr"), )) except Profile.DoesNotExist: return HttpResponseRedirect(reverse_lazy('email_update'))
Example #21
Source File: validators.py From pasportaservo with GNU Affero General Public License v3.0 | 5 votes |
def validate_size(content): """Validates if the size of the content in not too big.""" if content.file.size > validate_size.MAX_UPLOAD_SIZE: message = format_lazy( _("Please keep filesize under {limit}. Current filesize {current}"), limit=filesizeformat(validate_size.MAX_UPLOAD_SIZE), current=filesizeformat(content.file.size)) raise ValidationError(message, code='file-size')
Example #22
Source File: models.py From pasportaservo with GNU Affero General Public License v3.0 | 5 votes |
def get_locality_display(self): """ Returns "city (country)" or just "country" when no city is given. """ if self.city: return format_lazy("{city} ({state})", city=self.city, state=self.country.name) else: return self.country.name
Example #23
Source File: profiles.py From pasportaservo with GNU Affero General Public License v3.0 | 5 votes |
def clean(self): """ Sets specific fields as required when user wants their data to be printed in the paper edition. """ cleaned_data = super().clean() if hasattr(self, 'instance'): profile = self.instance for_book = profile.has_places_for_in_book all_filled = all([ cleaned_data.get(field, False) for field in self._validation_meta.book_required_fields ]) message = _("You want to be in the printed edition of Pasporta Servo. " "In order to have a quality product, some fields are required. " "If you think there is a problem, please contact us.") if for_book and not all_filled: if profile.has_places_for_hosting != profile.has_places_for_in_book: clarify_message = format_lazy( _("You are a host in {count_as_host} places, " "of which {count_for_book} should be in the printed edition."), count_as_host=profile.has_places_for_accepting_guests, count_for_book=profile.has_places_for_in_book) raise forms.ValidationError([message, clarify_message]) else: raise forms.ValidationError(message) if profile.death_date and 'birth_date' in cleaned_data: if cleaned_data['birth_date'] > profile.death_date: # Sanity check for life dates congruence. # xgettext:python-brace-format field_bd_message = _("The indicated date of birth is in conflict " "with the date of death ({:%Y-%m-%d}).") self.add_error( 'birth_date', format_lazy(field_bd_message, profile.death_date) ) return cleaned_data
Example #24
Source File: profiles.py From pasportaservo with GNU Affero General Public License v3.0 | 5 votes |
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) config = SiteConfiguration.get_solo() self.fields['first_name'].widget.attrs['inputmode'] = 'latin-name' self.fields['last_name'].widget.attrs['inputmode'] = 'latin-name' self.fields['names_inversed'].label = _("Names ordering") field_bd = self.fields['birth_date'] if hasattr(self, 'instance') and \ (self.instance.has_places_for_hosting or self.instance.has_places_for_meeting): if self.instance.has_places_for_hosting: message = _("The minimum age to be allowed hosting is {age:d}.") allowed_age = config.host_min_age else: message = _("The minimum age to be allowed meeting with visitors is {age:d}.") allowed_age = config.meet_min_age message = format_lazy(message, age=allowed_age) field_bd.required = True field_bd.validators.append(TooNearPastValidator(allowed_age)) field_bd.error_messages['max_value'] = message field_bd.widget.attrs['placeholder'] = 'jjjj-mm-tt' field_bd.widget.attrs['data-date-end-date'] = '0d' field_bd.widget.attrs['pattern'] = '[1-2][0-9]{3}-((0[1-9])|(1[0-2]))-((0[1-9])|([12][0-9])|(3[0-1]))' if hasattr(self, 'instance') and self.instance.has_places_for_in_book: message = _("This field is required to be printed in the book.") for field in self._validation_meta.book_required_fields: req_field = self.fields[field] req_field.required = True req_field.error_messages['required'] = message req_field.widget.attrs['data-error-required'] = message self.fields['avatar'].widget.attrs['accept'] = 'image/*'
Example #25
Source File: forms.py From pasportaservo with GNU Affero General Public License v3.0 | 5 votes |
def clean(self): cleaned_data = super().clean() if cleaned_data.get('country') in COUNTRIES_WITH_MANDATORY_REGION and not cleaned_data.get('state'): # Verifies that the region is indeed indicated when it is mandatory. message = _("For an address in {country}, the name of the state or province must be indicated.") self.add_error('state', format_lazy(message, country=Country(cleaned_data['country']).name)) return cleaned_data
Example #26
Source File: places.py From pasportaservo with GNU Affero General Public License v3.0 | 5 votes |
def get_success_url(self): success_url = reverse_lazy('authorize_user', kwargs={'pk': self.kwargs['pk']}) redirect_to = sanitize_next(self.request) if redirect_to: return format_lazy('{}?{}', success_url, next_link(self.request, redirect_to)) return success_url
Example #27
Source File: tables.py From manila-ui with Apache License 2.0 | 5 votes |
def allowed(self, request, share=None): usages = manila.tenant_absolute_limits(request) snapshots_allowed = (usages['maxTotalShareSnapshots'] > usages['totalShareSnapshotsUsed'] and usages['maxTotalSnapshotGigabytes'] > usages['totalSnapshotGigabytesUsed']) if not snapshots_allowed: if "disabled" not in self.classes: self.classes = [c for c in self.classes] + ['disabled'] self.verbose_name = format_lazy( '{verbose_name} {quota_exceeded}', verbose_name=self.verbose_name, quota_exceeded=_("(Quota exceeded)")) else: self.verbose_name = _("Create Share Snapshot") classes = [c for c in self.classes if c != "disabled"] self.classes = classes # NOTE(vponomaryov): Disable form with creation of a snapshot for # shares that has attr 'snapshot_support' equal to False. if hasattr(share, 'snapshot_support'): snapshot_support = share.snapshot_support else: # NOTE(vponomaryov): Allow creation of a snapshot for shares that # do not have such attr for backward compatibility. snapshot_support = True return share.status in ("available", "in-use") and snapshot_support
Example #28
Source File: options.py From python with Apache License 2.0 | 4 votes |
def contribute_to_class(self, cls, name): from django.db import connection from django.db.backends.utils import truncate_name cls._meta = self self.model = cls # First, construct the default values for these options. self.object_name = cls.__name__ self.model_name = self.object_name.lower() self.verbose_name = camel_case_to_spaces(self.object_name) # Store the original user-defined values for each option, # for use when serializing the model definition self.original_attrs = {} # Next, apply any overridden values from 'class Meta'. if self.meta: meta_attrs = self.meta.__dict__.copy() for name in self.meta.__dict__: # Ignore any private attributes that Django doesn't care about. # NOTE: We can't modify a dictionary's contents while looping # over it, so we loop over the *original* dictionary instead. if name.startswith('_'): del meta_attrs[name] for attr_name in DEFAULT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) self.original_attrs[attr_name] = getattr(self, attr_name) elif hasattr(self.meta, attr_name): setattr(self, attr_name, getattr(self.meta, attr_name)) self.original_attrs[attr_name] = getattr(self, attr_name) self.unique_together = normalize_together(self.unique_together) self.index_together = normalize_together(self.index_together) # verbose_name_plural is a special case because it uses a 's' # by default. if self.verbose_name_plural is None: self.verbose_name_plural = format_lazy('{}s', self.verbose_name) # order_with_respect_and ordering are mutually exclusive. self._ordering_clash = bool(self.ordering and self.order_with_respect_to) # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys())) else: self.verbose_name_plural = format_lazy('{}s', self.verbose_name) del self.meta # If the db_table wasn't provided, use the app_label + model_name. if not self.db_table: self.db_table = "%s_%s" % (self.app_label, self.model_name) self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
Example #29
Source File: options.py From Hands-On-Application-Development-with-PyCharm with MIT License | 4 votes |
def contribute_to_class(self, cls, name): from django.db import connection from django.db.backends.utils import truncate_name cls._meta = self self.model = cls # First, construct the default values for these options. self.object_name = cls.__name__ self.model_name = self.object_name.lower() self.verbose_name = camel_case_to_spaces(self.object_name) # Store the original user-defined values for each option, # for use when serializing the model definition self.original_attrs = {} # Next, apply any overridden values from 'class Meta'. if self.meta: meta_attrs = self.meta.__dict__.copy() for name in self.meta.__dict__: # Ignore any private attributes that Django doesn't care about. # NOTE: We can't modify a dictionary's contents while looping # over it, so we loop over the *original* dictionary instead. if name.startswith('_'): del meta_attrs[name] for attr_name in DEFAULT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) self.original_attrs[attr_name] = getattr(self, attr_name) elif hasattr(self.meta, attr_name): setattr(self, attr_name, getattr(self.meta, attr_name)) self.original_attrs[attr_name] = getattr(self, attr_name) self.unique_together = normalize_together(self.unique_together) self.index_together = normalize_together(self.index_together) # verbose_name_plural is a special case because it uses a 's' # by default. if self.verbose_name_plural is None: self.verbose_name_plural = format_lazy('{}s', self.verbose_name) # order_with_respect_and ordering are mutually exclusive. self._ordering_clash = bool(self.ordering and self.order_with_respect_to) # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs)) else: self.verbose_name_plural = format_lazy('{}s', self.verbose_name) del self.meta # If the db_table wasn't provided, use the app_label + model_name. if not self.db_table: self.db_table = "%s_%s" % (self.app_label, self.model_name) self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
Example #30
Source File: options.py From python2017 with MIT License | 4 votes |
def contribute_to_class(self, cls, name): from django.db import connection from django.db.backends.utils import truncate_name cls._meta = self self.model = cls # First, construct the default values for these options. self.object_name = cls.__name__ self.model_name = self.object_name.lower() self.verbose_name = camel_case_to_spaces(self.object_name) # Store the original user-defined values for each option, # for use when serializing the model definition self.original_attrs = {} # Next, apply any overridden values from 'class Meta'. if self.meta: meta_attrs = self.meta.__dict__.copy() for name in self.meta.__dict__: # Ignore any private attributes that Django doesn't care about. # NOTE: We can't modify a dictionary's contents while looping # over it, so we loop over the *original* dictionary instead. if name.startswith('_'): del meta_attrs[name] for attr_name in DEFAULT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) self.original_attrs[attr_name] = getattr(self, attr_name) elif hasattr(self.meta, attr_name): setattr(self, attr_name, getattr(self.meta, attr_name)) self.original_attrs[attr_name] = getattr(self, attr_name) self.unique_together = normalize_together(self.unique_together) self.index_together = normalize_together(self.index_together) # verbose_name_plural is a special case because it uses a 's' # by default. if self.verbose_name_plural is None: self.verbose_name_plural = format_lazy('{}s', self.verbose_name) # order_with_respect_and ordering are mutually exclusive. self._ordering_clash = bool(self.ordering and self.order_with_respect_to) # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys())) else: self.verbose_name_plural = format_lazy('{}s', self.verbose_name) del self.meta # If the db_table wasn't provided, use the app_label + model_name. if not self.db_table: self.db_table = "%s_%s" % (self.app_label, self.model_name) self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())