예제 #1
0
 def get_filters(self, request, use_distinct=False):
     filter_specs = []
     cleaned_params, use_distinct = self.get_lookup_params(use_distinct)
     if self.list_filter:
         for list_filer in self.list_filter:
             if callable(list_filer):
                 # This is simply a custom list filter class.
                 spec = list_filer(request, cleaned_params, self.model,
                                   self.model_admin)
             else:
                 field_path = None
                 if isinstance(list_filer, (tuple, list)):
                     # This is a custom FieldListFilter class for a given field.
                     field, field_list_filter_class = list_filer
                 else:
                     # This is simply a field name, so use the default
                     # FieldListFilter class that has been registered for
                     # the type of the given field.
                     field, field_list_filter_class = list_filer, FieldListFilter.create
                 if not isinstance(field, models.Field):
                     field_path = field
                     field = get_fields_from_path(self.model,
                                                  field_path)[-1]
                 spec = field_list_filter_class(field,
                                                request,
                                                cleaned_params,
                                                self.model,
                                                self.model_admin,
                                                field_path=field_path)
             if spec and spec.has_output():
                 filter_specs.append(spec)
     return filter_specs, bool(filter_specs)
예제 #2
0
파일: main.py 프로젝트: nexascale/nexathan
 def get_filters(self, request, use_distinct=False):
     filter_specs = []
     cleaned_params, use_distinct = self.get_lookup_params(use_distinct)
     if self.list_filter:
         for list_filer in self.list_filter:
             if callable(list_filer):
                 # This is simply a custom list filter class.
                 spec = list_filer(request, cleaned_params,
                     self.model, self.model_admin)
             else:
                 field_path = None
                 if isinstance(list_filer, (tuple, list)):
                     # This is a custom FieldListFilter class for a given field.
                     field, field_list_filter_class = list_filer
                 else:
                     # This is simply a field name, so use the default
                     # FieldListFilter class that has been registered for
                     # the type of the given field.
                     field, field_list_filter_class = list_filer, FieldListFilter.create
                 if not isinstance(field, models.Field):
                     field_path = field
                     field = get_fields_from_path(self.model, field_path)[-1]
                 spec = field_list_filter_class(field, request, cleaned_params,
                     self.model, self.model_admin, field_path=field_path)
             if spec and spec.has_output():
                 filter_specs.append(spec)
     return filter_specs, bool(filter_specs)
예제 #3
0
def validate(cls, model):
    """
    Does basic ModelAdmin option validation. Calls custom validation
    classmethod in the end if it is provided in cls. The signature of the
    custom validation classmethod should be: def validate(cls, model).
    """
    # Before we can introspect models, they need to be fully loaded so that
    # inter-relations are set up correctly. We force that here.
    models.get_apps()

    opts = model._meta
    validate_base(cls, model)

    # list_display
    if hasattr(cls, 'list_display'):
        check_isseq(cls, 'list_display', cls.list_display)
        for idx, field in enumerate(cls.list_display):
            if not callable(field):
                if not hasattr(cls, field):
                    if not hasattr(model, field):
                        try:
                            opts.get_field(field)
                        except models.FieldDoesNotExist:
                            raise ImproperlyConfigured("%s.list_display[%d], %r is not a callable or an attribute of %r or found in the model %r."
                                % (cls.__name__, idx, field, cls.__name__, model._meta.object_name))
                    else:
                        # getattr(model, field) could be an X_RelatedObjectsDescriptor
                        f = fetch_attr(cls, model, opts, "list_display[%d]" % idx, field)
                        if isinstance(f, models.ManyToManyField):
                            raise ImproperlyConfigured("'%s.list_display[%d]', '%s' is a ManyToManyField which is not supported."
                                % (cls.__name__, idx, field))

    # list_display_links
    if hasattr(cls, 'list_display_links'):
        check_isseq(cls, 'list_display_links', cls.list_display_links)
        for idx, field in enumerate(cls.list_display_links):
            if field not in cls.list_display:
                raise ImproperlyConfigured("'%s.list_display_links[%d]' "
                        "refers to '%s' which is not defined in 'list_display'."
                        % (cls.__name__, idx, field))

    # list_filter
    if hasattr(cls, 'list_filter'):
        check_isseq(cls, 'list_filter', cls.list_filter)
        for idx, item in enumerate(cls.list_filter):
            # There are three options for specifying a filter:
            #   1: 'field' - a basic field filter, possibly w/ relationships (eg, 'field__rel')
            #   2: ('field', SomeFieldListFilter) - a field-based list filter class
            #   3: SomeListFilter - a non-field list filter class
            if callable(item) and not isinstance(item, models.Field):
                # If item is option 3, it should be a ListFilter...
                if not issubclass(item, ListFilter):
                    raise ImproperlyConfigured("'%s.list_filter[%d]' is '%s'"
                            " which is not a descendant of ListFilter."
                            % (cls.__name__, idx, item.__name__))
                # ...  but not a FieldListFilter.
                if issubclass(item, FieldListFilter):
                    raise ImproperlyConfigured("'%s.list_filter[%d]' is '%s'"
                            " which is of type FieldListFilter but is not"
                            " associated with a field name."
                            % (cls.__name__, idx, item.__name__))
            else:
                if isinstance(item, (tuple, list)):
                    # item is option #2
                    field, list_filter_class = item
                    if not issubclass(list_filter_class, FieldListFilter):
                        raise ImproperlyConfigured("'%s.list_filter[%d][1]'"
                            " is '%s' which is not of type FieldListFilter."
                            % (cls.__name__, idx, list_filter_class.__name__))
                else:
                    # item is option #1
                    field = item
                # Validate the field string
                try:
                    get_fields_from_path(model, field)
                except (NotRelationField, FieldDoesNotExist):
                    raise ImproperlyConfigured("'%s.list_filter[%d]' refers to '%s'"
                            " which does not refer to a Field."
                            % (cls.__name__, idx, field))

    # list_per_page = 100
    if hasattr(cls, 'list_per_page') and not isinstance(cls.list_per_page, int):
        raise ImproperlyConfigured("'%s.list_per_page' should be a integer."
                % cls.__name__)

    # list_editable
    if hasattr(cls, 'list_editable') and cls.list_editable:
        check_isseq(cls, 'list_editable', cls.list_editable)
        for idx, field_name in enumerate(cls.list_editable):
            try:
                field = opts.get_field_by_name(field_name)[0]
            except models.FieldDoesNotExist:
                raise ImproperlyConfigured("'%s.list_editable[%d]' refers to a "
                    "field, '%s', not defined on %s."
                    % (cls.__name__, idx, field_name, model.__name__))
            if field_name not in cls.list_display:
                raise ImproperlyConfigured("'%s.list_editable[%d]' refers to "
                    "'%s' which is not defined in 'list_display'."
                    % (cls.__name__, idx, field_name))
            if field_name in cls.list_display_links:
                raise ImproperlyConfigured("'%s' cannot be in both '%s.list_editable'"
                    " and '%s.list_display_links'"
                    % (field_name, cls.__name__, cls.__name__))
            if not cls.list_display_links and cls.list_display[0] in cls.list_editable:
                raise ImproperlyConfigured("'%s.list_editable[%d]' refers to"
                    " the first field in list_display, '%s', which can't be"
                    " used unless list_display_links is set."
                    % (cls.__name__, idx, cls.list_display[0]))
            if not field.editable:
                raise ImproperlyConfigured("'%s.list_editable[%d]' refers to a "
                    "field, '%s', which isn't editable through the admin."
                    % (cls.__name__, idx, field_name))

    # search_fields = ()
    if hasattr(cls, 'search_fields'):
        check_isseq(cls, 'search_fields', cls.search_fields)

    # date_hierarchy = None
    if cls.date_hierarchy:
        f = get_field(cls, model, opts, 'date_hierarchy', cls.date_hierarchy)
        if not isinstance(f, (models.DateField, models.DateTimeField)):
            raise ImproperlyConfigured("'%s.date_hierarchy is "
                    "neither an instance of DateField nor DateTimeField."
                    % cls.__name__)

    # ordering = None
    if cls.ordering:
        check_isseq(cls, 'ordering', cls.ordering)
        for idx, field in enumerate(cls.ordering):
            if field == '?' and len(cls.ordering) != 1:
                raise ImproperlyConfigured("'%s.ordering' has the random "
                        "ordering marker '?', but contains other fields as "
                        "well. Please either remove '?' or the other fields."
                        % cls.__name__)
            if field == '?':
                continue
            if field.startswith('-'):
                field = field[1:]
            # Skip ordering in the format field1__field2 (FIXME: checking
            # this format would be nice, but it's a little fiddly).
            if '__' in field:
                continue
            get_field(cls, model, opts, 'ordering[%d]' % idx, field)

    if hasattr(cls, "readonly_fields"):
        check_readonly_fields(cls, model, opts)

    # list_select_related = False
    # save_as = False
    # save_on_top = False
    for attr in ('list_select_related', 'save_as', 'save_on_top'):
        if not isinstance(getattr(cls, attr), bool):
            raise ImproperlyConfigured("'%s.%s' should be a boolean."
                    % (cls.__name__, attr))


    # inlines = []
    if hasattr(cls, 'inlines'):
        check_isseq(cls, 'inlines', cls.inlines)
        for idx, inline in enumerate(cls.inlines):
            if not issubclass(inline, BaseModelAdmin):
                raise ImproperlyConfigured("'%s.inlines[%d]' does not inherit "
                        "from BaseModelAdmin." % (cls.__name__, idx))
            if not inline.model:
                raise ImproperlyConfigured("'model' is a required attribute "
                        "of '%s.inlines[%d]'." % (cls.__name__, idx))
            if not issubclass(inline.model, models.Model):
                raise ImproperlyConfigured("'%s.inlines[%d].model' does not "
                        "inherit from models.Model." % (cls.__name__, idx))
            validate_base(inline, inline.model)
            validate_inline(inline, cls, model)