Django Admin filter_horizo​​ntal无效

时间:2015-06-22 13:52:58

标签: python django

我正在尝试将滤镜水平设置为包含搜索和选定的分区,而不是使用ctrl多个选项选择的单个列。

我在admin.py中包含了过滤器水平,但它不起作用。我正在使用从admin.ModelAdmin导入的公共类可能会出现问题吗?

class ArticleAdmin(CommonAdmin):
    form = autocomplete_light.modelform_factory(Article)
    list_display = [
        'name',
        'categories_display',
        'modified_by',
        'created_by',
        'modified',
        'created',
        'visible',
    ]
    list_editable = ['visible']
    filter_horizontal = ('categories','tags')
    #list_filter = ('categories',)
    excludes = ['sortorder',]
    inlines = [
        HotItemInline,
        ArticleImageInline,
        ArticleYoutubeVideoInline,
        #RelatedArticleInline
    ]

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "categories":
            try:
                category_root = Category.objects.get(slug='lifestyle')
                kwargs["queryset"] = Category.objects.filter(tree_id=category_root.tree_id).exclude(id=category_root.id)
            except Category.DoesNotExist:
                pass
        return super(CommonAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

普通管理员

class CommonAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.ImageField: {'widget': PreviewImageWidget},
    }
    list_display = ['name', 'modified_by', 'created_by', 'modified', 'created', 'visible', 'get_absolute_url']
    search_fields = ['name', ]
    list_filter = ['modified', 'created', 'visible']
    ordering = ['-modified',]
    actions=[make_invisible, make_visible,]
    list_select_related = True

    class Media:
        js = (
            "/static/kb/js/admin/timeoptions.js",
        )

    def changelist_view(self, request, extra_context=None):
        if not request.GET.has_key('visible__exact'):
            q = request.GET.copy()
            q['visible__exact'] = 1
            request.GET = q
            request.META['QUERY_STRING'] = request.GET.urlencode()
        return super(CommonAdmin,self).changelist_view(request, extra_context=extra_context)

    def save_model(self, request, obj, form, change):
        if not obj.id:
            obj.created_by = request.user
            obj.created = datetime.datetime.today()
        obj.modified_by = request.user
        obj.modified = datetime.datetime.today()
        if hasattr(obj, 'name') and hasattr(obj, 'header') and hasattr(obj, 'title'):
            if not obj.header:
                obj.header = obj.name
            if not obj.title:
                obj.title = obj.name
        obj.save()

和模型

class Article(BaseItemModel):
    area = TreeForeignKey(Area, blank=True, null=True,)
    categories = TreeManyToManyField(Category)
    tags = models.ManyToManyField(Tag, blank=True)
    author = models.CharField(max_length=255, blank=True,)
    html = RichTextField(blank=True, null=True,)

    def share_content(self):
        html = self.html
        if not html:
            html = self.content
        return html.replace('"', "'").strip()

    @models.permalink
    def get_absolute_url(self):
        return ('article_detail', (), {'slug': self.slug})

1 个答案:

答案 0 :(得分:3)

这是一个较旧的问题,但我只需处理同样的情况。答案是在ModelAdmin上定义filter_horizontal以及直接在TreeNodeMultipleChoiceField上设置小部件,Article处理mptt选项的缩进显示。

以下是使用问题中的from django import forms, admin from mptt.forms import TreeNodeMultipleChoiceField class ArticleAdminForm(forms.ModelForm): categories = TreeNodeMultipleChoiceField(required=False, queryset = Category.objects.all(), level_indicator = u'+--', widget = admin.widgets.FilteredSelectMultiple('Categories', False)) class Meta: model = Article fields = '__all__' class ArticleAdmin(admin.ModelAdmin): filter_horizontal = ('categories',) form = ArticleAdminForm 模型的解决方案:

DECLARE @allUsers XML=
'<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">
 <Worksheet>
 <Table>
   <Row ss:AutoFitHeight="0" ss:Height="30">
    <Cell ss:StyleID="s22"/>
    <Cell ss:StyleID="s24"><Data ss:Type="String">Jane Doe</Data></Cell>
    <Cell ss:StyleID="s24"><Data ss:Type="String">JaneDoe</Data></Cell>
    <Cell ss:StyleID="s24"><Data ss:Type="String">XYZ</Data></Cell>
    <Cell ss:StyleID="s24"><Data ss:Type="String">(555) 555-5555</Data></Cell>
    <Cell ss:StyleID="s22"/>
   </Row>
   </Table>
 </Worksheet>   
</Workbook>';

;WITH XMLNAMESPACES ('urn:schemas-microsoft-com:office:spreadsheet' as ss
                     ,DEFAULT 'urn:schemas-microsoft-com:office:spreadsheet')
SELECT T.X.value('Cell[1]/Data[1]','varchar(max)') AS DontKnow1
      ,T.X.value('Cell[2]/Data[1]','varchar(max)') AS Name
      ,T.X.value('Cell[3]/Data[1]','varchar(max)') AS UserName
      ,T.X.value('Cell[4]/Data[1]','varchar(max)') AS DontKnow2
      ,T.X.value('Cell[5]/Data[1]','varchar(max)') AS Telephone
      ,T.X.value('Cell[6]/Data[1]','varchar(max)') AS DontKnow3
FROM @allUsers.nodes('/Workbook/Worksheet/Table/Row') as T(X)