我想在下拉菜单中添加一个项目链接以导出 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
看起来像
如何解决这个问题呢?