1

我想在下拉菜单中添加一个项目链接以导出 CSV 中的所有记录这是管理员的代码:

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)

如果您手动输入网址“/admin/competition/entrant/export”,则功能有效

如何使用 url 在 dropdwon 菜单链接中添加新菜单项:/admin/competition/entrant/export

看起来像

我想要那个红色菜单项

如何解决这个问题呢?

4

1 回答 1

0

要回答您的直接问题,您可以在菜单中添加一个自定义项,其中将您的网址作为命名网址。

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管理操作。这将是一个小技巧,因为您需要至少选择一个项目以确保操作正确触发。但是,如果这是一个员工管理员,那么教育他们如何使用它会很容易。在操作中,您只需忽略 queryset 参数。

于 2013-06-20T05:17:01.257 回答