我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.text.capfirst()。
def date_error_message(self, lookup_type, field_name, unique_for): opts = self._meta field = opts.get_field(field_name) return ValidationError( message=field.error_messages['unique_for_date'], code='unique_for_date', params={ 'model': self, 'model_name': six.text_type(capfirst(opts.verbose_name)), 'lookup_type': lookup_type, 'field': field_name, 'field_label': six.text_type(capfirst(field.verbose_name)), 'date_field': unique_for, 'date_field_label': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)), } )
def block_top_navbar(self, context, nodes): search_models = [] site_name = self.admin_site.name if self.global_search_models == None: models = self.admin_site._registry.keys() else: models = self.global_search_models for model in models: app_label = model._meta.app_label if self.has_model_perm(model, "view"): info = (app_label, model._meta.model_name) if getattr(self.admin_site._registry[model], 'search_fields', None): try: search_models.append({ 'title': _('Search %s') % capfirst(model._meta.verbose_name_plural), 'url': reverse('xadmin:%s_%s_changelist' % info, current_app=site_name), 'model': model }) except NoReverseMatch: pass return nodes.append(loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'search_models': search_models, 'search_name': SEARCH_VAR}))
def block_top_navmenu(self, context, nodes): add_models = [] site_name = self.admin_site.name if self.global_add_models == None: models = self.admin_site._registry.keys() else: models = self.global_add_models for model in models: app_label = model._meta.app_label if self.has_model_perm(model, "add"): info = (app_label, model._meta.model_name) try: add_models.append({ 'title': _('Add %s') % capfirst(model._meta.verbose_name), 'url': reverse('xadmin:%s_%s_add' % info, current_app=site_name), 'model': model }) except NoReverseMatch: pass nodes.append( loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'add_models': add_models}))
def style_labels(label_map, style=LabelStyleType.DEFAULT_STYLE): style_labels = {} for name, verbose_name in label_map.iteritems(): if style == LabelStyleType.TITLE: label = verbose_name.title() elif style == LabelStyleType.CAPFIRST: label = capfirst(verbose_name) elif style == LabelStyleType.LOWER: label = verbose_name.lower() else: raise Exception('Invalid style: {}'.format(style)) if style != LabelStyleType.LOWER and 'dbms' in label.lower(): label = label.replace('dbms', 'DBMS') label = label.replace('Dbms', 'DBMS') style_labels[name] = label return style_labels
def filter_for_reverse_field(cls, f, name): """Handles retrieving filters for reverse relationships We override the default implementation so that we can handle Global IDs (the default implementation expects database primary keys) """ rel = f.field.rel default = { 'name': name, 'label': capfirst(rel.related_name) } if rel.multiple: # For to-many relationships return GlobalIDMultipleChoiceFilter(**default) else: # For to-one relationships return GlobalIDFilter(**default)
def block_top_navbar(self, context, nodes): search_models = [] site_name = self.admin_site.name if self.global_search_models == None: models = self.admin_site._registry.keys() else: models = self.global_search_models for model in models: app_label = model._meta.app_label if self.has_model_perm(model, "view"): info = (app_label, model._meta.module_name) if getattr(self.admin_site._registry[model], 'search_fields', None): try: search_models.append({ 'title': _('Search %s') % capfirst(model._meta.verbose_name_plural), 'url': reverse('xadmin:%s_%s_changelist' % info, current_app=site_name), 'model': model }) except NoReverseMatch: pass nodes.append(loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'search_models': search_models, 'search_name': SEARCH_VAR}))
def block_top_navmenu(self, context, nodes): add_models = [] site_name = self.admin_site.name if self.global_add_models == None: models = self.admin_site._registry.keys() else: models = self.global_add_models for model in models: app_label = model._meta.app_label if self.has_model_perm(model, "add"): info = (app_label, model._meta.module_name) try: add_models.append({ 'title': _('Add %s') % capfirst(model._meta.verbose_name), 'url': reverse('xadmin:%s_%s_add' % info, current_app=site_name), 'model': model }) except NoReverseMatch: pass nodes.append( loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'add_models': add_models}))
def make_cropping_field(cls, size_key, origin_field_name="image", verbose_name=None, help_text=None): """ Creates a image_cropping.fields.ImageRatioField that allows cropping of images in the admin forms. NB: make sure to call self.crop_image_if_needed in the save method of models using these fields """ size = cls._image_sizes[size_key] if not verbose_name: verbose_name = " ".join(map(capfirst, size_key.split("_"))) verbose_name = "%s crop" % verbose_name if not help_text: help_text = "Crops image to %s×%s" % (size[0], size[1]) return ImageRatioField( image_field=origin_field_name, size="%sx%s" % (size[0], size[1]), size_warning=True, verbose_name=verbose_name, help_text=help_text, )
def block_top_navbar(self, context, nodes): search_models = [] site_name = self.admin_site.name if self.global_search_models == None: models = list(self.admin_site._registry.keys()) else: models = self.global_search_models for model in models: app_label = model._meta.app_label if self.has_model_perm(model, "view"): info = (app_label, model._meta.model_name) if getattr(self.admin_site._registry[model], 'search_fields', None): try: search_models.append({ 'title': _('Search %s') % capfirst(model._meta.verbose_name_plural), 'url': reverse('xadmin:%s_%s_changelist' % info, current_app=site_name), 'model': model }) except NoReverseMatch: pass return nodes.append(loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'search_models': search_models, 'search_name': SEARCH_VAR}))
def block_top_navmenu(self, context, nodes): add_models = [] site_name = self.admin_site.name if self.global_add_models == None: models = list(self.admin_site._registry.keys()) else: models = self.global_add_models for model in models: app_label = model._meta.app_label if self.has_model_perm(model, "add"): info = (app_label, model._meta.model_name) try: add_models.append({ 'title': _('Add %s') % capfirst(model._meta.verbose_name), 'url': reverse('xadmin:%s_%s_add' % info, current_app=site_name), 'model': model }) except NoReverseMatch: pass nodes.append( loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'add_models': add_models}))
def field_kwargs(self): kwargs = {'label': capfirst(' '.join(self.property.key.split('_'))), 'help_text': self.property.doc} with suppress(AttributeError): enum_class = self.column.type.enum_class if enum_class is not None: kwargs['enum_class'] = self.column.type.enum_class else: kwargs['choices'] = self.column.type.enums with suppress(AttributeError): kwargs['max_digits'] = self.column.type.precision with suppress(AttributeError): kwargs['decimal_places'] = self.column.type.scale with suppress(AttributeError): kwargs['max_length'] = self.column.type.length kwargs['required'] = not self.column.nullable kwargs['allow_null'] = self.column.nullable return kwargs
def add_fields(self, form, index): super(BaseInlineFormSet, self).add_fields(form, index) if self._pk_field == self.fk: name = self._pk_field.name kwargs = {'pk_field': True} else: # The foreign key field might not be on the form, so we poke at the # Model field to get the label, since we need that for error messages. name = self.fk.name kwargs = { 'label': getattr(form.fields.get(name), 'label', capfirst(self.fk.verbose_name)) } if self.fk.rel.field_name != self.fk.rel.to._meta.pk.name: kwargs['to_field'] = self.fk.rel.field_name form.fields[name] = InlineForeignKeyField(self.instance, **kwargs) # Add the generated field to form._meta.fields if it's defined to make # sure validation isn't skipped on that field. if form._meta.fields: if isinstance(form._meta.fields, tuple): form._meta.fields = list(form._meta.fields) form._meta.fields.append(self.fk.name)
def formfield(self, **kwargs): """Form field instance for this model field""" if self.choices: form_class = ( kwargs.pop('choices_form_class', None) or cf_forms.CollectionChoiceField ) else: form_class = ( kwargs.pop('form_class', None) or cf_forms.CollectionField ) if getattr(form_class, 'collection_field_compatible', False): defaults = { 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text, # CollectionField-specific params: 'collection_type': self.collection_type, 'item_type': self.item_type, 'sort': self.sort, 'unique_items': self._has_unique_items(), 'max_items': self.max_items, 'max_length': self.max_length, } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() if self.choices: defaults['choices'] = self.get_choices(include_blank=False) defaults.update(kwargs) return form_class(**defaults) else: return super(CollectionField, self).formfield(**kwargs)
def add_fields(self, form, index): super(BaseInlineFormSet, self).add_fields(form, index) if self._pk_field == self.fk: name = self._pk_field.name kwargs = {'pk_field': True} else: # The foreign key field might not be on the form, so we poke at the # Model field to get the label, since we need that for error messages. name = self.fk.name kwargs = { 'label': getattr(form.fields.get(name), 'label', capfirst(self.fk.verbose_name)) } if self.fk.remote_field.field_name != self.fk.remote_field.model._meta.pk.name: kwargs['to_field'] = self.fk.remote_field.field_name # If we're adding a new object, ignore a parent's auto-generated key # as it will be regenerated on the save request. if self.instance._state.adding: if kwargs.get('to_field') is not None: to_field = self.instance._meta.get_field(kwargs['to_field']) else: to_field = self.instance._meta.pk if to_field.has_default(): setattr(self.instance, to_field.attname, None) form.fields[name] = InlineForeignKeyField(self.instance, **kwargs) # Add the generated field to form._meta.fields if it's defined to make # sure validation isn't skipped on that field. if form._meta.fields: if isinstance(form._meta.fields, tuple): form._meta.fields = list(form._meta.fields) form._meta.fields.append(self.fk.name)
def __init__(self, request=None, *args, **kwargs): """ The 'request' parameter is set for custom auth use by subclasses. The form data comes in via the standard 'data' kwarg. """ self.request = request self.user_cache = None super(AuthenticationForm, self).__init__(*args, **kwargs) # Set the label for the "username" field. UserModel = get_user_model() self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD) if self.fields['username'].label is None: self.fields['username'].label = capfirst(self.username_field.verbose_name)
def get_action(self, action): """ Return a given action from a parameter, which can either be a callable, or the name of a method on the ModelAdmin. Return is a tuple of (callable, name, description). """ # If the action is a callable, just use it. if callable(action): func = action action = action.__name__ # Next, look for a method. Grab it off self.__class__ to get an unbound # method instead of a bound one; this ensures that the calling # conventions are the same for functions and methods. elif hasattr(self.__class__, action): func = getattr(self.__class__, action) # Finally, look for a named method on the admin site else: try: func = self.admin_site.get_action(action) except KeyError: return None if hasattr(func, 'short_description'): description = func.short_description else: description = capfirst(action.replace('_', ' ')) return func, action, description
def history_view(self, request, object_id, extra_context=None): "The 'history' admin view for this model." from django.contrib.admin.models import LogEntry # First check if the user can see this history. model = self.model obj = self.get_object(request, unquote(object_id)) if obj is None: raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % { 'name': force_text(model._meta.verbose_name), 'key': escape(object_id), }) if not self.has_change_permission(request, obj): raise PermissionDenied # Then get the history for this object. opts = model._meta app_label = opts.app_label action_list = LogEntry.objects.filter( object_id=unquote(object_id), content_type=get_content_type_for_model(model) ).select_related().order_by('action_time') context = dict(self.admin_site.each_context(request), title=_('Change history: %s') % force_text(obj), action_list=action_list, module_name=capfirst(force_text(opts.verbose_name_plural)), object=obj, opts=opts, preserved_filters=self.get_preserved_filters(request), ) context.update(extra_context or {}) request.current_app = self.admin_site.name return TemplateResponse(request, self.object_history_template or [ "admin/%s/%s/object_history.html" % (app_label, opts.model_name), "admin/%s/object_history.html" % app_label, "admin/object_history.html" ], context)
def formfield(self, **kwargs): defaults = { 'form_class': forms.NullBooleanField, 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} defaults.update(kwargs) return super(NullBooleanField, self).formfield(**defaults)
def unique_error_message(self, model_class, unique_check): opts = model_class._meta params = { 'model': self, 'model_class': model_class, 'model_name': six.text_type(capfirst(opts.verbose_name)), 'unique_check': unique_check, } # A unique field if len(unique_check) == 1: field = opts.get_field(unique_check[0]) params['field_label'] = six.text_type(capfirst(field.verbose_name)) return ValidationError( message=field.error_messages['unique'], code='unique', params=params, ) # unique_together else: field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check] params['field_labels'] = six.text_type(get_text_list(field_labels, _('and'))) return ValidationError( message=_("%(model_name)s with this %(field_labels)s already exists."), code='unique_together', params=params, )
def add_fields(self, form, index): super(BaseInlineFormSet, self).add_fields(form, index) if self._pk_field == self.fk: name = self._pk_field.name kwargs = {'pk_field': True} else: # The foreign key field might not be on the form, so we poke at the # Model field to get the label, since we need that for error messages. name = self.fk.name kwargs = { 'label': getattr(form.fields.get(name), 'label', capfirst(self.fk.verbose_name)) } if self.fk.remote_field.field_name != self.fk.remote_field.model._meta.pk.name: kwargs['to_field'] = self.fk.remote_field.field_name # If we're adding a new object, ignore a parent's auto-generated key # as it will be regenerated on the save request. if self.instance._state.adding: if kwargs.get('to_field') is not None: to_field = self.instance._meta.get_field(kwargs['to_field']) else: to_field = self.instance._meta.pk if to_field.has_default(): setattr(self.instance, to_field.attname, None) form.fields[name] = InlineForeignKeyField(self.instance, **kwargs)
def history_view(self, request, object_id, extra_context=None): "The 'history' admin view for this model." from django.contrib.admin.models import LogEntry # First check if the user can see this history. model = self.model obj = self.get_object(request, unquote(object_id)) if obj is None: raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % { 'name': force_text(model._meta.verbose_name), 'key': escape(object_id), }) if not self.has_change_permission(request, obj): raise PermissionDenied # Then get the history for this object. opts = model._meta app_label = opts.app_label action_list = LogEntry.objects.filter( object_id=unquote(object_id), content_type=get_content_type_for_model(model) ).select_related().order_by('action_time') context = dict( self.admin_site.each_context(request), title=_('Change history: %s') % force_text(obj), action_list=action_list, module_name=capfirst(force_text(opts.verbose_name_plural)), object=obj, opts=opts, preserved_filters=self.get_preserved_filters(request), ) context.update(extra_context or {}) request.current_app = self.admin_site.name return TemplateResponse(request, self.object_history_template or [ "admin/%s/%s/object_history.html" % (app_label, opts.model_name), "admin/%s/object_history.html" % app_label, "admin/object_history.html" ], context)
def get_model_method_fields(self): """ Return the fields info defined in model. use FakeMethodField class wrap method as a db field. """ methods = [] for name in dir(self): try: if getattr(getattr(self, name), 'is_column', False): methods.append((name, getattr(self, name))) except: pass return [FakeMethodField(name, getattr(method, 'short_description', capfirst(name.replace('_', ' ')))) for name, method in methods]
def get_context(self): context = super(RecoverListView, self).get_context() opts = self.opts deleted = self._order_version_queryset(Version.objects.get_deleted(self.model)) context.update({ "opts": opts, "app_label": opts.app_label, "model_name": capfirst(opts.verbose_name), "title": _("Recover deleted %(name)s") % {"name": force_text(opts.verbose_name_plural)}, "deleted": deleted, "changelist_url": self.model_admin_url("changelist"), }) return context
def get_context(self): context = super(RevisionListView, self).get_context() opts = self.opts action_list = [ { "revision": version.revision, "url": self.model_admin_url('revision', quote(version.object_id), version.id), "version": version } for version in self._reversion_order_version_queryset(Version.objects.get_for_object_reference( self.model, self.obj.pk, ).select_related("revision__user")) ] context.update({ 'title': _('Change history: %s') % force_text(self.obj), 'action_list': action_list, 'model_name': capfirst(force_text(opts.verbose_name_plural)), 'object': self.obj, 'app_label': opts.app_label, "changelist_url": self.model_admin_url("changelist"), "update_url": self.model_admin_url("change", self.obj.pk), 'opts': opts, }) return context
def __init__(self, request=None, *args, **kwargs): """ The 'request' parameter is set for custom auth use by subclasses. The form data comes in via the standard 'data' kwarg. """ self.request = request self.user_cache = None super(AuthenticationForm, self).__init__(*args, **kwargs) # Set the label for the "username" field. self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD) if self.fields['username'].label is None: self.fields['username'].label = capfirst(self.username_field.verbose_name)