我通常更喜欢在管理员中执行此 *** 作。这是片段:
def download_csv(modeladmin, request, queryset): if not request.user.is_staff: raise PermissionDenied opts = queryset.model._meta model = queryset.model response = HttpResponse(mimetype='text/csv') # force download. response['Content-Disposition'] = 'attachment;filename=export.csv' # the csv writer writer = csv.writer(response) field_names = [field.name for field in opts.fields] # Write a first row with header information writer.writerow(field_names) # Write data rows for obj in queryset: writer.writerow([getattr(obj, field) for field in field_names]) return responsedownload_csv.short_description = "Download selected as csv"
在您的视图功能中使用它
def myview(request): data = download_csv(ModelAdmin, request, Model.objects.all()) return HttpResponse (data, content_type='text/csv')
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)