コード例 #1
0
ファイル: utils.py プロジェクト: dbsiavichay/django-hydra
def get_label_of_field(model, field):
    names = field.split(".")
    name = names.pop(0)

    try:
        name, verbose_name = name.split(":")
        return pretty_name(verbose_name)
    except ValueError:
        pass

    if not hasattr(model, name):
        try:
            str_model = f"<{model._meta.model_name}>"
        except:
            str_model = str(model)
        raise AttributeError(
            f"No existe le atributo <{name}> para {str_model}.")

    if len(names):
        if hasattr(model, "_meta"):
            return get_label_of_field(
                model._meta.get_field(name).related_model, ".".join(names))
        else:
            attr = getattr(model, name)
            return get_label_of_field(attr() if callable(attr) else attr,
                                      ".".join(names))
    try:
        field = model._meta.get_field(name)
        label = field.verbose_name if hasattr(field, "verbose_name") else name
    except FieldDoesNotExist:
        label = str(model._meta.verbose_name) if name == "__str__" else name

    return pretty_name(label)
コード例 #2
0
 def get_field_label(cls, model, field):
     try:
         name, verbose_name = field.split(cls.LABEL_SEPARATOR)
         return pretty_name(verbose_name)
     except ValueError:
         pass
     if "__str__" in field:
         label = str(model._meta.verbose_name)
         return pretty_name(label)
     names = field.split(cls.FIELD_SEPARATOR)
     name = names.pop(0)
     if not hasattr(model, name):
         str_model = (model._meta.model_name
                      if hasattr(model, "_meta") else str(model))
         raise AttributeError(
             f"Does not exist attribute <{name}> for {str_model}.")
     try:
         field = model._meta.get_field(name)
         if len(names):
             related_model = field.related_model
             return cls.get_field_label(related_model,
                                        cls.FIELD_SEPARATOR.join(names))
         label = field.verbose_name
     except FieldDoesNotExist:
         attr = getattr(object, name)
         if len(names):
             return cls.get_field_label(
                 attr(model) if callable(attr) else attr,
                 cls.FIELD_SEPARATOR.join(names),
             )
         label = name
     return pretty_name(label)
コード例 #3
0
ファイル: utils.py プロジェクト: 50mkw/mysite
def label_for_field(name, model, model_rec=None, return_attr=False, form=None):
    """
    Return a sensible label for a field name. The name can be a callable,
    property (but not created with @property decorator), or the name of an
    object's attribute, as well as a model field. If return_attr is True, also
    return the resolved attribute (which could be a callable). This will be
    None if (and only if) the name refers to a field.
    """
    attr = None
    try:
        field = _get_non_gfk_field(model._meta, name)
        try:
            label = field.verbose_name
        except AttributeError:
            # field is likely a ForeignObjectRel
            label = field.related_model._meta.verbose_name
    except FieldDoesNotExist:
        if name == "__str__":
            label = str(model._meta.verbose_name)
            attr = str
        else:
            if callable(name):
                attr = name
            elif hasattr(model_rec, name):
                attr = getattr(model_rec, name)
            elif hasattr(model, name):
                attr = getattr(model, name)
            elif form and name in form.fields:
                attr = form.fields[name]
            else:
                message = "Unable to lookup '%s' on %s" % (name, model._meta.object_name)
                if model_rec:
                    message += " or %s" % (model_rec.__class__.__name__,)
                if form:
                    message += " or %s" % form.__class__.__name__
                raise AttributeError(message)

            if hasattr(attr, "short_description"):
                label = attr.short_description
            elif (isinstance(attr, property) and
                  hasattr(attr, "fget") and
                  hasattr(attr.fget, "short_description")):
                label = attr.fget.short_description
            elif callable(attr):
                if attr.__name__ == "<lambda>":
                    label = "--"
                else:
                    label = pretty_name(attr.__name__)
            else:
                label = pretty_name(name)
    except FieldIsAForeignKeyColumnName:
        label = pretty_name(name)
        attr = name

    if return_attr:
        return (label, attr)
    else:
        return label
コード例 #4
0
ファイル: utils.py プロジェクト: Chrescht/django
def label_for_field(name, model, model_admin=None, return_attr=False, form=None):
    """
    Return a sensible label for a field name. The name can be a callable,
    property (but not created with @property decorator), or the name of an
    object's attribute, as well as a model field. If return_attr is True, also
    return the resolved attribute (which could be a callable). This will be
    None if (and only if) the name refers to a field.
    """
    attr = None
    try:
        field = _get_non_gfk_field(model._meta, name)
        try:
            label = field.verbose_name
        except AttributeError:
            # field is likely a ForeignObjectRel
            label = field.related_model._meta.verbose_name
    except FieldDoesNotExist:
        if name == "__str__":
            label = str(model._meta.verbose_name)
            attr = str
        else:
            if callable(name):
                attr = name
            elif hasattr(model_admin, name):
                attr = getattr(model_admin, name)
            elif hasattr(model, name):
                attr = getattr(model, name)
            elif form and name in form.fields:
                attr = form.fields[name]
            else:
                message = "Unable to lookup '%s' on %s" % (name, model._meta.object_name)
                if model_admin:
                    message += " or %s" % (model_admin.__class__.__name__,)
                if form:
                    message += " or %s" % form.__class__.__name__
                raise AttributeError(message)

            if hasattr(attr, "short_description"):
                label = attr.short_description
            elif (isinstance(attr, property) and
                  hasattr(attr, "fget") and
                  hasattr(attr.fget, "short_description")):
                label = attr.fget.short_description
            elif callable(attr):
                if attr.__name__ == "<lambda>":
                    label = "--"
                else:
                    label = pretty_name(attr.__name__)
            else:
                label = pretty_name(name)
    except FieldIsAForeignKeyColumnName:
        label = pretty_name(name)
        attr = name

    if return_attr:
        return (label, attr)
    else:
        return label
コード例 #5
0
def label_for_field(name, model, view_controller=None, return_attr=False):
    """
    Returns a sensible label for a field name. The name can be a callable,
    property (but not created with @property decorator) or the name of an
    object's attribute, as well as a genuine fields. If return_attr is
    True, the resolved attribute (which could be a callable) is also returned.
    This will be None if (and only if) the name refers to a field.
    """
    attr = None
    try:
        field = _get_non_gfk_field(model._meta, name)
        try:
            label = field.verbose_name
        except AttributeError:
            # field is likely a ForeignObjectRel
            label = field.related_model._meta.verbose_name
    except FieldDoesNotExist:
        if name == "__unicode__":
            label = force_text(model._meta.verbose_name)
            attr = six.text_type
        elif name == "__str__":
            label = force_str(model._meta.verbose_name)
            attr = bytes
        else:
            if callable(name):
                attr = name
            elif view_controller is not None and hasattr(view_controller, name):
                attr = getattr(view_controller, name)
            elif hasattr(model, name):
                attr = getattr(model, name)
            else:
                message = "Unable to lookup '%s' on %s" % (name, model._meta.object_name)
                if view_controller:
                    message += " or %s" % (view_controller.__class__.__name__,)
                raise AttributeError(message)

            if hasattr(attr, "short_description"):
                label = attr.short_description
            elif (isinstance(attr, property) and
                  hasattr(attr, "fget") and
                  hasattr(attr.fget, "short_description")):
                label = attr.fget.short_description
            elif callable(attr):
                if attr.__name__ == "<lambda>":
                    label = "--"
                else:
                    label = pretty_name(attr.__name__)
            else:
                label = pretty_name(name)
    if return_attr:
        return (label, attr)
    else:
        return label
コード例 #6
0
def _get_attr_label(owner, attr_name):
    attr = getattr(owner, attr_name)
    if hasattr(attr, "short_description"):
        return attr.short_description
    elif isinstance(attr, property) and hasattr(attr, "fget"):
        if hasattr(attr.fget, "short_description"):
            return attr.fget.short_description
        else:
            return pretty_name(attr.fget.__name__)
    elif callable(attr):
        return "--" if attr.__name__ == "<lambda>" else pretty_name(attr.__name__)
    else:
        return attr_name
コード例 #7
0
ファイル: utils.py プロジェクト: bartosh/django
def label_for_field(name, model, model_admin=None, return_attr=False):
    """
    Returns a sensible label for a field name. The name can be a callable,
    property (but not created with @property decorator) or the name of an
    object's attribute, as well as a genuine fields. If return_attr is
    True, the resolved attribute (which could be a callable) is also returned.
    This will be None if (and only if) the name refers to a field.
    """
    attr = None
    try:
        field = _get_non_gfk_field(model._meta, name)
        try:
            label = field.verbose_name
        except AttributeError:
            # field is likely a ForeignObjectRel
            label = field.related_model._meta.verbose_name
    except FieldDoesNotExist:
        if name == "__unicode__":
            label = force_text(model._meta.verbose_name)
            attr = six.text_type
        elif name == "__str__":
            label = force_str(model._meta.verbose_name)
            attr = bytes
        else:
            if callable(name):
                attr = name
            elif model_admin is not None and hasattr(model_admin, name):
                attr = getattr(model_admin, name)
            elif hasattr(model, name):
                attr = getattr(model, name)
            else:
                message = "Unable to lookup '%s' on %s" % (name, model._meta.object_name)
                if model_admin:
                    message += " or %s" % (model_admin.__class__.__name__,)
                raise AttributeError(message)

            if hasattr(attr, "short_description"):
                label = attr.short_description
            elif isinstance(attr, property) and hasattr(attr, "fget") and hasattr(attr.fget, "short_description"):
                label = attr.fget.short_description
            elif callable(attr):
                if attr.__name__ == "<lambda>":
                    label = "--"
                else:
                    label = pretty_name(attr.__name__)
            else:
                label = pretty_name(name)
    if return_attr:
        return (label, attr)
    else:
        return label
コード例 #8
0
 def _get_resource_label(self, model, field_name):
     resource = self.get_resource(model)
     if resource:
         method_field = resource.get_method_returning_field_value(field_name)
         return getattr(method_field, 'short_description', pretty_name(field_name)) if method_field else None
     else:
         return None
コード例 #9
0
def get_headers(fields):
    for field in fields:
        yield {
            'text': pretty_name(field),
            'class_attrib': format_html(' class="column-{}"', field),
            'sortable': False,
        }
コード例 #10
0
ファイル: views.py プロジェクト: mostateresnet/rimproject
    def get(self, request, *args, **kwargs):
        if self.export_csv:
            keys = ['serial_no', 'hostname', 'equipment_model', 'manufacturer',
                    'equipment_type__type_name', 'latest_checkout__client__name',
                    'latest_checkout__client__bpn', 'latest_checkout__location__building', 'latest_checkout__location__room']
            verbose_keys = []
            for key in keys:
                split_key = key.split('__')
                field = Equipment._meta.get_field(split_key[0])
                while True:
                    if len(split_key) > 1:
                        field = field.remote_field.model._meta.get_field(split_key[1])
                        split_key = split_key[1:]
                    else:
                        verbose_keys.append(field._verbose_name or pretty_name(field.verbose_name))
                        break

            equipment_list = self.get_queryset().values(*keys)
            current_time = localtime(now()).strftime("%Y-%m-%d-%I%M")
            response = HttpResponse(content_type='text/csv')
            response['Content-Disposition'] = 'attachment; filename="RIMreport_' + current_time + '.csv"'

            writer = csv.DictWriter(response, fieldnames=keys)
            writer.writerow(dict(zip(keys, verbose_keys)))

            for equipment in equipment_list:
                writer.writerow(equipment)
            return response
        else:
            return super().get(request, *args, **kwargs)
コード例 #11
0
ファイル: forms.py プロジェクト: ella/django-appdata
 def add_fields(self, form, index):
     """appcontainer fields are no longer added to the empty form, we can inject them hooking here."""
     super(AppDataBaseInlineFormSet, self).add_fields(form, index)
     for name, field in form.base_fields.items():
         if name not in form.fields:
             form.fields[name] = deepcopy(field)
             if not form.fields[name].label:
                 form.fields[name].label = pretty_name(name.split('.')[1])
コード例 #12
0
ファイル: panels.py プロジェクト: danmorley/nhs-example
    def __init__(self, attr, heading=None, classname='', help_text=''):
        self.attr = attr
        self.heading = pretty_name(self.attr) if heading is None else heading
        self.classname = classname
        self.help_text = help_text

        def required_fields(self):
            raise AttributeError
コード例 #13
0
ファイル: ordering.py プロジェクト: earshinov/django_sample
 def __init__(self, param_name: str, data: typing.Mapping[str, typing.Any]):
     exprs = data.get('exprs') or data.get('expr')
     if not exprs:
         raise ValueError("Expected 'exprs' or 'expr'")
     self.exprs = normalize_exprs(exprs)
     self.label = data.get('label', _(pretty_name(param_name)))
     self.desc_label = data.get('desc_label',
                                descending_fmt.format(self.label))
コード例 #14
0
ファイル: forms.py プロジェクト: gabrielluiz123/PortalMarcas
 def add_fields(self, form, index):
     """appcontainer fields are no longer added to the empty form, we can inject them hooking here."""
     super(AppDataBaseInlineFormSet, self).add_fields(form, index)
     for name, field in form.base_fields.items():
         if name not in form.fields:
             form.fields[name] = deepcopy(field)
             if not form.fields[name].label:
                 form.fields[name].label = pretty_name(name.split('.')[1])
コード例 #15
0
ファイル: models.py プロジェクト: wdjlover/django-erp-1
def get_field_tuple(name, form_or_model):
    """Returns a tuple for the field, of given instance, identified by "name".
    
    Instance could be a model instance, a form instance or any arbitrary object.
    
    The returned tuple is in the form:
    
    (label, attrs, value)
    """
    name, sep, suffix = name.partition(':')

    label = ""
    value = ""
    td_attrs = {}
    field_list = get_fields(form_or_model)
    field = None

    if name in field_list:
        field = field_list[name]

    elif hasattr(form_or_model, name):
        field = getattr(form_or_model, name)
        if hasattr(field, 'short_description'):
            name = field.short_description

    if isinstance(field, models.Field):
        label = '%s:' % field.verbose_name
        value = '%s' % field_to_string(field, form_or_model)

    elif isinstance(field, forms.Field):
        bf = BoundField(form_or_model, field, name)
        label = '%s' % bf.label_tag()
        value = '%s' % bf
        if bf.help_text:
            value += '<br/><span title="%(help_text)s" class="helptext helppopup">%(help_text)s</span>' % {
                "help_text": '%s' % bf.help_text
            }
        errors = bf.errors
        if errors:
            value += '<br/>\n<ul class="errorlist">\n'
            for error in errors:
                value += '\t<li>%s</li>\n' % error
            value += '</ul>\n'
        css_classes = bf.css_classes()
        if css_classes:
            td_attrs['class'] = css_classes

    else:
        name = _(pretty_name(name).lower())
        label = '%s:' % name.capitalize()
        value = field() if callable(field) else field

    firstcap_label = label[:1].upper() + label[1:]
    if suffix:
        value += " " + suffix

    return mark_safe(firstcap_label), flatatt(td_attrs), mark_safe(value)
コード例 #16
0
    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)

        label = self._label
        if label is None:
            label = pretty_name(name)
        context['widget']['label'] = label

        return context
コード例 #17
0
ファイル: filters.py プロジェクト: Charnelx/django-filter
    def build_choices(self, fields, labels):
        ascending = [(param, labels.get(field, _(pretty_name(param))))
                     for field, param in fields.items()]
        descending = [('-%s' % param,
                       labels.get('-%s' % param, self.descending_fmt % label))
                      for param, label in ascending]

        # interleave the ascending and descending choices
        return [val for pair in zip(ascending, descending) for val in pair]
コード例 #18
0
def worldline_pretty_name(val):
    all_caps_strings = ["mid", "tid", "msf", "rrn", "mcc"]
    if str(val).lower() in all_caps_strings:
        return str(val).upper()
    elif str(val).lower() == "pmid":
        return "Parent MID"
    elif str(val).lower() == "merchant_dba_name":
        return "Merchant DBA Name"
    else:
        return pretty_name(val).title()
コード例 #19
0
ファイル: borgcube.py プロジェクト: enkore/borgcube
def field_name(obj, field):
    try:
        name = obj.Form.declared_fields[field].label
    except AttributeError as ae:
        name = None
    name = name or field
    if name == field.replace('_', ' '):
        return name.title()
    if name == field:
        return pretty_name(name)
    return name
コード例 #20
0
def _set_help_labels(self, help_links):
    for field in self.fields:
        if field in help_links:
            if not self.fields[field].label:
                label = pretty_name(field)
            else:
                label = self.fields[field].label
            self.fields[field].label = mark_safe(
                label +
                ' <a href="%s%s" target=_blank>[?]</a>' %
                (DOC_URL, help_links[field]))
コード例 #21
0
            def get_form_class(self):
                val_to_name = inverse_mapping(plain_filter_map)
                fields = OrderedDict()

                for name, filter_ in self.filters.items():
                    f = filter_.field
                    f.label = pretty_name(val_to_name[name])

                    fields.update({val_to_name[name]: f})

                return type(str('%sForm' % self.__class__.__name__),
                            (self._meta.form, ), fields)
コード例 #22
0
ファイル: filters.py プロジェクト: ZoeGeng/Art
    def build_choices(self, fields, labels):
        ascending = [
            (param, labels.get(field, _(pretty_name(param))))
            for field, param in fields.items()
        ]
        descending = [
            ('-%s' % param, labels.get('-%s' % param, self.descending_fmt % label))
            for param, label in ascending
        ]

        # interleave the ascending and descending choices
        return [val for pair in zip(ascending, descending) for val in pair]
コード例 #23
0
ファイル: boundfield.py プロジェクト: zc-andy/DbMgrSystem
 def __init__(self, form, field, name):
     self.form = form
     self.field = field
     self.name = name
     self.html_name = form.add_prefix(name)
     self.html_initial_name = form.add_initial_prefix(name)
     self.html_initial_id = form.add_initial_prefix(self.auto_id)
     if self.field.label is None:
         self.label = pretty_name(name)
     else:
         self.label = self.field.label
     self.help_text = field.help_text or ''
コード例 #24
0
ファイル: boundfield.py プロジェクト: charsten/django
 def __init__(self, form, field, name):
     self.form = form
     self.field = field
     self.name = name
     self.html_name = form.add_prefix(name)
     self.html_initial_name = form.add_initial_prefix(name)
     self.html_initial_id = form.add_initial_prefix(self.auto_id)
     if self.field.label is None:
         self.label = pretty_name(name)
     else:
         self.label = self.field.label
     self.help_text = field.help_text or ''
コード例 #25
0
    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]
コード例 #26
0
    def formfield_for_manytomany(self, db_field, request=None, **kwargs):
        """
        Get a form Field for a ManyToManyField.
        """
        db = kwargs.get('using')

        if db_field.name in self.raw_id_fields:
            kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel, using=db)
            kwargs['help_text'] = ''
        elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
            kwargs['widget'] = widgets.FilteredSelectMultiple(pretty_name(db_field.name), (db_field.name in self.filter_vertical))

        return db_field.formfield(**kwargs)
コード例 #27
0
ファイル: views.py プロジェクト: xzregg/djmyframework
    def decorator(func):
        func.mapping = MethodMapper(func, methods)

        func.detail = detail
        func.url_path = url_path if url_path else func.__name__
        func.url_name = url_name if url_name else func.__name__
        func.kwargs = kwargs

        # Set descriptive arguments for viewsets
        if 'name' not in kwargs and 'suffix' not in kwargs:
            func.kwargs['name'] = pretty_name(func.__name__)
        func.kwargs['description'] = func.__doc__ or None

        return func
コード例 #28
0
    def decorator(func):
        func.mapping = MethodMapper(func, methods)

        func.detail = detail
        func.url_path = url_path if url_path else func.__name__
        func.url_name = url_name if url_name else func.__name__.replace('_', '-')
        func.kwargs = kwargs

        # Set descriptive arguments for viewsets
        if 'name' not in kwargs and 'suffix' not in kwargs:
            func.kwargs['name'] = pretty_name(func.__name__)
        func.kwargs['description'] = func.__doc__ or None

        return func
コード例 #29
0
ファイル: decorators.py プロジェクト: cecpanda/lantern
    def decorator(func):
        func.mapping = MethodMapper(func, methods)

        func.detail = detail
        func.name = name if name else pretty_name(func.__name__)
        func.url_path = url_path if url_path else func.__name__
        func.url_name = url_name if url_name else func.__name__.replace('_', '-')
        func.kwargs = kwargs
        func.kwargs.update({
            'name': func.name,
            'description': func.__doc__ or None
        })

        return func
コード例 #30
0
ファイル: util.py プロジェクト: starryrbs/django-mongoengine
def label_for_field(name, model, model_admin=None, return_attr=False):
    attr = None
    try:
        field = model._meta.get_field_by_name(name)[0]
        label = field.name.replace('_', ' ')
    except FieldDoesNotExist:
        if name == "__unicode__":
            label = force_text(model._meta.verbose_name)
        elif name == "__str__":
            label = smart_str(model._meta.verbose_name)
        else:
            if callable(name):
                attr = name
            elif model_admin is not None and hasattr(model_admin, name):
                attr = getattr(model_admin, name)
            elif hasattr(model, name):
                attr = getattr(model, name)
            else:
                message = "Unable to lookup '%s' on %s" % (
                    name, model._meta.object_name)
                if model_admin:
                    message += " or %s" % (model_admin.__class__.__name__, )
                raise AttributeError(message)

            if hasattr(attr, "short_description"):
                label = attr.short_description
            elif callable(attr):
                if attr.__name__ == "<lambda>":
                    label = "--"
                else:
                    label = pretty_name(attr.__name__)
            else:
                label = pretty_name(name)
    if return_attr:
        return (label, attr)
    else:
        return label
コード例 #31
0
            def get_form_class(self):
                val_to_name = inverse_mapping(plain_filter_map)
                fields = OrderedDict()

                for name, filter_ in self.filters.items():
                    f = filter_.field

                    # set label for field using filter_map
                    # eg. if map is {"name": "profile__name"} then set label to "Name", by default it is "Profile Name"
                    f.label = pretty_name(val_to_name[name])

                    fields.update({val_to_name[name]: f})

                return type(str('%sForm' % self.__class__.__name__),
                            (self._meta.form, ), fields)
コード例 #32
0
    def validate_unique(self):
        """
        Validates unique constrains on the document.
        unique_with is supported now.
        """
        errors = []
        exclude = self._get_validation_exclusions()
        for f in self.instance._fields.values():
            if f.unique and f.name not in exclude:
                filter_kwargs = {
                    f.name: getattr(self.instance, f.name),
                    'q_obj': None,
                }
                if f.unique_with:
                    for u_with in f.unique_with:
                        u_with_field = self.instance._fields[u_with]
                        u_with_attr = getattr(self.instance, u_with)
                        # handling ListField(ReferenceField()) sucks big time
                        # What we need to do is construct a Q object that
                        # queries for the pk of every list entry and only
                        # accepts lists with the same length as our list
                        if isinstance(u_with_field, ListField) and \
                                isinstance(u_with_field.field, ReferenceField):
                            q_list = [Q(**{u_with: k.pk}) for k in u_with_attr]
                            q = reduce(lambda x, y: x & y, q_list)
                            size_key = '%s__size' % u_with
                            q = q & Q(**{size_key: len(u_with_attr)})
                            filter_kwargs['q_obj'] = q & filter_kwargs['q_obj']
                        else:
                            filter_kwargs[u_with] = u_with_attr
                qs = self.instance.__class__.objects.clone()
                qs = qs.no_dereference().filter(**filter_kwargs)
                # Exclude the current object from the query if we are editing
                # an instance (as opposed to creating a new one)
                if self.instance.pk is not None:
                    qs = qs.filter(pk__ne=self.instance.pk)
                if qs.count() > 0:
                    message = _("%s with this %s already exists.") % (
                        str(capfirst(self.instance._meta.verbose_name)),
                        str(pretty_name(f.name))
                    )
                    err_dict = {f.name: [message]}
                    self._update_errors(err_dict)
                    errors.append(err_dict)

        return errors
コード例 #33
0
    def decorator(func):
        func.mapping = MethodMapper(func, methods)

        func.detail = detail
        func.url_path = url_path if url_path else func.__name__
        func.url_name = url_name if url_name else func.__name__.replace('_', '-')

        # These kwargs will end up being passed to `ViewSet.as_view()` within
        # the router, which eventually delegates to Django's CBV `View`,
        # which assigns them as instance attributes for each request.
        func.kwargs = kwargs

        # Set descriptive arguments for viewsets
        if 'name' not in kwargs and 'suffix' not in kwargs:
            func.kwargs['name'] = pretty_name(func.__name__)
        func.kwargs['description'] = func.__doc__ or None

        return func
コード例 #34
0
ファイル: fields.py プロジェクト: django-parler/django-parler
    def short_description(self):
        """
        Ensure that the admin ``list_display`` renders the correct verbose name for translated fields.

        The :func:`~django.contrib.admin.utils.label_for_field` function
        uses :func:`~django.db.models.Options.get_field_by_name` to find the find and ``verbose_name``.
        However, for translated fields, this option does not exist,
        hence it falls back to reading the attribute and trying ``short_description``.
        Ideally, translated fields should also appear in this list, to be treated like regular fields.
        """
        translations_model = self.field.meta.model
        if translations_model is None:
            # This only happens with abstract models. The code is accessing the descriptor at the base model directly,
            # not the upgraded descriptor version that contribute_translations() installed.
            # Fallback to what the admin label_for_field() would have done otherwise.
            return pretty_name(self.field.name)

        field = translations_model._meta.get_field(self.field.name)
        return field.verbose_name
コード例 #35
0
def label_for_field(view, queryset, field_name):
    """
    Returns the suitable lable for a field. Labels are determined as per the
    following rules:
        1. Model's meta class is searched for a field with matching name.
           If found, fields verbose_name is used as label

        2. A method on the model class with the same name is looked up.
           If found, the method's 'label' attribute value is used as the label.

        3. Viewset is searched for a method with the same name.
           If found, the method's 'label' attribute value is used as the label.

        4. If none of the above match, the specified field name is used as is.
    """
    options = queryset.model._meta
    try:
        field = options.get_field(field_name)
        if isinstance(field, RelatedField):
            label = field.related_model._meta.verbose_name
        else:
            label = field.verbose_name
    except FieldDoesNotExist:
        model = queryset.model
        # query the model for a method with matching name
        if hasattr(model, field_name) and callable(getattr(model, field_name)):
            # method exists, return its 'label' attribute value
            label = getattr(getattr(model, field_name), 'label',
                            field_name.title())
        # query the viewset for a method with matching name
        elif hasattr(view._viewset, field_name) and \
            callable(getattr(view._viewset, field_name)):
            # method exists, return its 'label' attribute value
            label = getattr(getattr(view._viewset, field_name), 'label',
                            field_name.title())
        else:
            label = pretty_name(field_name)

    return {
        'text': label,
        'sortable': False,
        'class_attrib': 'class=col-{}'.format(field_name)
    }
コード例 #36
0
ファイル: filters.py プロジェクト: ZoeGeng/Art
    def normalize_lookup(cls, lookup):
        """
        Normalize the lookup into a tuple of ``(lookup expression, display value)``

        If the ``lookup`` is already a tuple, the tuple is not altered.
        If the ``lookup`` is a string, a tuple is returned with the lookup
        expression used as the basis for the display value.

        ex::

            >>> LookupChoiceFilter.normalize_lookup(('exact', 'Equals'))
            ('exact', 'Equals')

            >>> LookupChoiceFilter.normalize_lookup('has_key')
            ('has_key', 'Has key')

        """
        if isinstance(lookup, str):
            return (lookup, pretty_name(lookup))
        return (lookup[0], lookup[1])
コード例 #37
0
    def normalize_lookup(cls, lookup):
        """
        Normalize the lookup into a tuple of ``(lookup expression, display value)``

        If the ``lookup`` is already a tuple, the tuple is not altered.
        If the ``lookup`` is a string, a tuple is returned with the lookup
        expression used as the basis for the display value.

        ex::

            >>> LookupChoiceFilter.normalize_lookup(('exact', 'Equals'))
            ('exact', 'Equals')

            >>> LookupChoiceFilter.normalize_lookup('has_key')
            ('has_key', 'Has key')

        """
        if isinstance(lookup, str):
            return (lookup, pretty_name(lookup))
        return (lookup[0], lookup[1])
コード例 #38
0
ファイル: utils.py プロジェクト: vinay-pad/django
def label_for_filter(model, field_name, lookup_expr, exclude=False):
    """
    Create a generic label suitable for a filter.

    ex::

        >>> label_for_filter(Article, 'author__name', 'in')
        'auther name is in'

    """
    name = verbose_field_name(model, field_name)
    verbose_expression = [_('exclude'), name] if exclude else [name]

    # iterable lookups indicate a LookupTypeField, which should not be verbose
    if isinstance(lookup_expr, six.string_types):
        verbose_expression += [verbose_lookup_expr(lookup_expr)]

    verbose_expression = [force_text(part) for part in verbose_expression if part]
    verbose_expression = pretty_name(' '.join(verbose_expression))

    return verbose_expression
コード例 #39
0
from __future__ import unicode_literals
コード例 #40
0
from __future__ import unicode_literals