夹层管理菜单自定义链接

时间:2013-06-19 12:56:11

标签: python django mezzanine

我想在下拉菜单中添加一个项链接,以CSV格式导出所有记录,这是admin的代码:

class EntrantAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'email' , 'date_of_birth', 'postcode')
readonly_fields = ('date_of_birth', 'answer')
search_fields = ['email','first_name', 'last_name']

def get_urls(self):
    urlpatterns = patterns('',
        url(r'^export/$', self.admin_site.admin_view(self.export),
            name='competition_entrant_export'),
    )
    urlpatterns += super(EntrantAdmin, self).get_urls()
    return urlpatterns

def export(self, request, *args, **kwargs):
    # Get all the field names from the Entrant model so we can export them
    # in our csv file. We don't want the database primary key, though.
    fields = map(attrgetter('name'), Entrant._meta.fields)
    fields.remove('id')

    # Construct a File-like object, in this case a Response, to write
    # our csv data to. Also specify that it should be treated as an
    # attachment (if not in debug mode).
    stream = HttpResponse(mimetype='text/csv')
    if not settings.DEBUG:
        filename = 'competition.csv'
        stream['Content-Disposition'] = 'attachment; filename=' + filename

    writer = csv.DictWriter(stream, fields, dialect=quoteall)
    try:
        writer.writeheader()
    except AttributeError:  # Python < 2.7
        writer.writerow(dict(zip(fields,fields)))
    writer.writerows(Entrant.objects.values(*fields))

    return stream
admin.site.register(Entrant, EntrantAdmin)

如果输入url manualy“/ admin / competition / entrant / export”

,功能就有效

如何使用url:/ admin / competition / entrant / export

在dropdwon菜单链接中添加新菜单项

看起来像

I want that red menu item

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

要回答您的直接问题,您可以在菜单中添加custom item,将您的网址作为已命名的网址。

ADMIN_MENU_ORDER = (
    ("Content", ("pages.Page", "blog.BlogPost", "blog.Comment",
        ("Export Entrants", "competition_entrant_export"),)),
    ("Site", ("auth.User", "auth.Group", "sites.Site", "redirects.Redirect")),
)

另一个简单的方法是使用django admin action。这将是一个小小的黑客攻击,因为您需要选择至少一个项目以确保操作正确触发。但如果这是一名员工管理员,那么教他们如何使用它会很容易。在操作中,您将忽略queryset参数。