我们从Python开源项目中,提取了以下32个代码示例,用于说明如何使用django.utils.translation.string_concat()。
def get_data(self): data = super(GlobalOverview, self).get_data() # Pre-fill project names try: projects, has_more = api.keystone.tenant_list(self.request) except Exception: projects = [] exceptions.handle(self.request, _('Unable to retrieve project list.')) for instance in data: project = [t for t in projects if t.id == instance.tenant_id] # If we could not get the project name, show the tenant_id with # a 'Deleted' identifier instead. if project: instance.project_name = getattr(project[0], "name", None) else: deleted = _("Deleted") instance.project_name = translation.string_concat( instance.tenant_id, " (", deleted, ")") return data
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 `string_concat` does. For example, proxied # ungettext calls require a count parameter and are converted # to an empty string if they are missing it. message=string_concat( 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 ])
def formfield_for_manytomany(self, db_field, **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 'queryset' not in kwargs: queryset = self.get_field_queryset(db, db_field) 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 = string_concat(help_text, ' ', msg) if help_text else msg return form_field
def formfield_for_manytomany(self, db_field, request=None, **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) kwargs['help_text'] = '' 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 = string_concat(help_text, ' ', msg) if help_text else msg return form_field
def stats_percent(self): try: evolved_choices = [False, True] if self.evolvable else [False] if not self._local_stats: self._local_stats = [(evolved, [{ 'stat': field, 'name': name, 'value_max_level': self._value_at_level(field, level=self.max_level, is_evolved=evolved), 'percent_max_level': 100, 'javascript_levels': str({str(level): { 'value': self._value_at_level(field, level=level, is_evolved=evolved), 'percent': (float(self._value_at_level(field, level=level, is_evolved=evolved, to_string=False)) / django_settings.MAX_STATS.get( field + '_max')) * 100.0, } for level in range(1, self.max_level + 1)}).replace('\'', '"'), } for (field, name) in [ ('hp', string_concat(_('HP'), ' ', _('evolved') if evolved else '')), ('sp', string_concat(_('SP'), ' ', _('evolved') if evolved else '')), ('atk', string_concat(_('ATK'), ' ', _('evolved') if evolved else '')), ('def', string_concat(_('DEF'), ' ', _('evolved') if evolved else '')), ] ]) for evolved in evolved_choices] return self._local_stats except ZeroDivisionError: return None # Raw values
def formfield_for_manytomany(self, db_field, request=None, **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.rel.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.rel, self.admin_site, using=db) kwargs['help_text'] = '' 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 = string_concat(help_text, ' ', msg) if help_text else msg return form_field
def __init__(self, queryset, cache_choices=False, required=True, widget=None, label=None, initial=None, help_text='', *args, **kwargs): super(ModelMultipleChoiceField, self).__init__(queryset, None, cache_choices, required, widget, label, initial, help_text, *args, **kwargs) # Remove this in Django 1.8 if isinstance(self.widget, SelectMultiple) and not isinstance(self.widget, CheckboxSelectMultiple): msg = _('Hold down "Control", or "Command" on a Mac, to select more than one.') self.help_text = string_concat(self.help_text, ' ', msg)
def formfield_for_manytomany(self, db_field, request=None, **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 hasattr(db_field, 'through') and 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) kwargs['help_text'] = '' 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 = string_concat(help_text, ' ', msg) if help_text else msg return form_field
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 = string_concat(self.verbose_name, 's') # 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 = string_concat(self.verbose_name, 's') 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())
def __unicode__(self): if self.name is None or get_language() == 'ja': return self.japanese_name else: return self.name ############################################################ # Action Skill # class ActionSkill(MagiModel): # collection_name = 'action_skill' # # name = models.CharField(_('Action Skill'), max_length=100) # japanese_name = models.CharField(string_concat(_('Action Skill'), ' (', t['Japanese'], ')'), max_length=100) # # def __unicode__(self): # if get_language() == 'ja': # return self.japanese_name # else: # return self.name # # damage = models.CharField(_('Skill Damage'), max_length=200) # combo = models.PositiveIntegerField(_('Skill Combo'), default=13) # effects = models.ManyToManyField('ActionSkillEffect', related_name='skills_with_effect', null=True) ############################################################ # Action Skill Effect # class ActionSkillEffect(MagiModel): # collection_name = 'action_skill_effect' # # i_name = models.CharField(_('Action Skill Effect'), max_length=100) # # bonus_value = models.PositiveIntegerField(_('Effect Value'), null=True) # duration = models.PositiveIntegerField(_('Effect Duration'), null=True) # skill_affinity = models.PositiveIntegerField(_('Skill Affinity'), null=True, choices=SKILL_AFFINITY_CHOICES, # default=IGNORE_AFFINITY) # # def __unicode__(self): # return '{} {}'.format(self.i_name, self.bonus_value) ############################################################ # Weapons
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) ut = meta_attrs.pop('unique_together', self.unique_together) self.unique_together = normalize_together(ut) it = meta_attrs.pop('index_together', self.index_together) self.index_together = normalize_together(it) # 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 = string_concat(self.verbose_name, 's') # 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 = string_concat(self.verbose_name, 's') 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())