示例#1
0
 def __init(self, field, request, params, model, model_admin, field_path):
     # 首先执行父类的__init__()
     super().__init__(field, request, params, model, model_admin, field_path)
     # 重新d定义self.lookup_choices的值,这个值在默认情况下(也就是在父类中)查询所有的数据。根据owner过滤
     self.lookup_choices = Category.objects.filter(owner=request.user).value_list('id', 'name')
     # 把定义的过滤器注册到过滤器管理器中,并且设置优先权,这样才会在页面加载时使用我们定义的这个过滤器
     manager.register(CategoryOwnerFilter, take_priority=True)
示例#2
0
        return super(TagAdmin, self).save_model(request, obj, form, change)


class CategoryOwnerFilter(RelatedFieldListFilter):
    @classmethod
    def test(cls, field, request, params, model, admin_view, field_path):
        return field.name == 'category'

    def __init__(self, field, request, params, model, model_admin, field_path):
        super().__init__(field, request, params, model, model_admin,
                         field_path)
        self.lookup_choices = Category.objects.filter(
            owner=request.user).values_list('id', 'name')


manager.register(CategoryOwnerFilter, take_priority=True)

# title = '分类过滤器'
# parameter_name = 'owner_category'
#
# def lookups(self, request, model_admin):
#     return Category.objects.filter(owner=request.user).values_list('id','name')
#
# def queryset(self, request, queryset):
#     category_id = self.value()
#     if category_id:
#         return queryset.filter(category_id=self.value())
#     return queryset


@xadmin.sites.register(Post)
示例#3
0
                         field_path, field_order_by, field_limit, sort_key,
                         cache_config)
        queryset = self.admin_view.queryset().exclude(
            **{
                "%s__isnull" % field_path: True
            }).values_list(field_path,
                           flat=True).order_by(field_path).distinct()
        for it in queryset:
            print(it)
        self.lookup_choices = [
            str(it) for it in queryset.values_list('tag__name', flat=True)
            if str(it).strip() != ""
        ]


manager.register(TagOwnerFilter, take_priority=True)


@xadmin.sites.register(Post)
class PostAdmin(BaseOwnerAdmin):
    form = PostAdminForm
    list_display = [
        'title',
        'category',
        'tag',
        'status',
        'created_time',
        'owner',
        'operator',
        'is_top',
    ]
示例#4
0
class CategoryAuthorFilter(RelatedFieldListFilter):
    """ 自定义过滤器只展示当前用户分类 """
    @classmethod
    def test(cls, field, request, params, model, admin_view, field_path):
        return field.name == 'category'

    def __init__(self, field, request, params, model, model_admin, field_path):
        super(CategoryAuthorFilter,
              self).__init__(field, request, params, model, model_admin,
                             field_path)
        self.lookup_choices = Category.objects.filter(
            author=request.user).values_list('id', 'name')


manager.register(CategoryAuthorFilter, take_priority=True)


class PostAdmin(BaseOwnerAdmin):

    form = PostAdminForm

    # <class 'article.admin.PostAdmin'>: (admin.E109) The value of 'list_display[3]' must not be a ManyToManyField.
    # list_display 不能包含ManyToMany字段
    list_display = [
        'title', 'author', 'category', 'summary', 'pv', 'uv', 'created_time',
        'operator'
    ]
    list_filter = ['category']
    list_display_links = [
        'title',
示例#5
0
        for url in values:
            yield {
                'selected': url == self.lookup_exact_val,
                'query_string': self.query_string({self.lookup_exact_name: url}),
                'display': url,
            }

    def do_filte(self, queryset):
        if 'url__exact' in self.used_params:
            visit_page = self.used_params['url__exact'].strip()
            if visit_page == '非/':
                return queryset.exclude(url=' / ')
            else:
                return queryset
        return queryset.filter(**self.used_params)
manager.register(UrlFilter, take_priority=True)


class ArticleAdmin(object):
    list_display = ['id', 'cat', 'tag', 'titles', 'desc',
                    'icon_url', 'view_count', 'event_date']
    list_display_links = ['id']

    def icon_url(self, obj):
        return '<img src="%s" height=50/>' % obj.icon.url

    icon_url.allow_tags = True
    icon_url.short_description = '缩略图'

    def titles(self, obj):
        return """
示例#6
0
class PostAdmin(BaseOwnerModelAdmin):
    form = PostAdminForm

    list_display = ('title', 'status', 'category', 'owner', 'created_time',
                    'operator')
    list_display_links = []

    form_layout = (Fieldset(
        '基础信息',
        Row('title', 'category'),
        'status',
        'tag',
    ), Fieldset('内容信息', 'desc', 'is_md', 'content_ck', 'content_md',
                'content'))

    # admin 过滤器
    # class PostOwnerFilter(SimpleListFilter):
    #     title = '分类'
    #     parameter_name = 'owner_category'
    #     def lookups(self, request, model_admin):
    #         return Category.objects.filter(owner=request.user).values_list('id','name')
    #
    #     def queryset(self, request, queryset):
    #         if self.value():
    #             return queryset.filter(category_id=self.value())
    #         return queryset

    # list_filter = [PostOwnerFilter,]

    # xadmin过滤器
    class CategoryOwnerFilter(RelatedFieldListFilter):
        @classmethod
        def test(cls, field, request, params, model, admin_view, field_path):
            return field.name == 'category'

        def __init__(self, field, request, params, model, mode_admin,
                     field_path):
            super().__init__(field, request, params, model, mode_admin,
                             field_path)
            self.lookup_choices = Category.objects.filter(
                owner=request.user).values_list('id', 'name')

    manager.register(CategoryOwnerFilter, take_priority=True)

    # xadmin的过滤字段的写法,此处只写过滤器过滤的字段名,而不是过滤器名
    list_filter = ['category']

    search_fields = ['title', 'category__name']

    actions_on_top = True
    actions_on_bottom = True

    save_on_top = True

    fields = (
        'category',
        'title',
        'desc',
        'status',
        'is_md',
        'content',
        'tag',
        'created_time',
    )

    # xadmin 的编写方法 和 admin中的fieldset 的区别
    form_layout = (Fieldset(
        '基础信息',
        Row('title', 'category'),
        'status',
        'tag',
    ), Fieldset(
        '内容信息',
        'desc',
        'is_md',
        'content',
    ))

    # 配置静态资源(兼容admin和xadmin)
    # @property
    # def media(self):
    #     media=super().media
    #     media.add_js(['the path of the js file',])
    #     media.add_css({'all':('the path of css file',)})
    #     return media

    # filter_horizontal = ('tag',)

    def operator(self, obj):
        if obj.id:
            return format_html(
                '<a href={}>编辑</a>',
                # 法一
                # reverse('xadmin:main_post_change',args=(obj.id,))
                # xadmin 中更友好的方法
                self.model_admin_url('change', obj.id))
        return None

    operator.short_description = '操作'
示例#7
0
#     title = "分类过滤器"
#     parameter_name = 'owner_category'  # 查询时url参数的名字
#
#     def lookups(self, request, model_admin):
#         # 返回要展示的内容和查询用的id,url传的参数
#         return Category.objects.filter(owner=request.user).values_list('id', 'name')
#
#     def queryset(self, request, queryset):
#         # 根据url query 的内容返回列表页数据
#         category_id = self.value()  # ?owner_category=1
#         if category_id:
#             return queryset.filter(category_id=self.value())
#         return queryset

# xadmin    通过对字段名的检测来动态创建对应的过滤器
class CategoryOwnerFilter(RelatedFieldListFilter):
    """自定义过滤器只展示当前用户分类"""

    @classmethod
    def test(cls, field, request, params, model, admin_view, field_path):
        """确认字段是否需要被当前的过滤器处理"""
        return field.name == 'category'

    def __init__(self, field, request, params, model, admin_view, field_path):
        super().__init__(field, request, params, model, admin_view, field_path)
        # 重新获取lookup_choices 根据owner过滤
        self.lookup_choices = Category.objects.filter(owner=request.user).values_list('id', 'name')


manager.register(CategoryOwnerFilter, take_priority=True)  # 注册,并设置优先权