Skip to content

Instantly share code, notes, and snippets.

@macagua
Last active September 1, 2019 00:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macagua/79a8830cb0da80f3d2830a09c85d68fa to your computer and use it in GitHub Desktop.
Save macagua/79a8830cb0da80f3d2830a09c85d68fa to your computer and use it in GitHub Desktop.
Returning CSV format from django-rest-framework
# project/settings.py
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
'rest_framework_csv.renderers.CSVRenderer',
)
}
# app/urls.py
# GET /api/csv/download/1/
# - Download csv file upload.
url(r'^api/csv/download/(?P<uploadfile_id>\d+)/$', views.FilesProcessedView.download_csv_file,
name="download_csv_file"),
# app/views.py
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.views import APIView
from rest_framework_csv.renderers import CSVRenderer
from models import MyModel
from serializers import MyModelSerializer
class FilesProcessedView(APIView):
...
...
...
@api_view(('GET',))
@renderer_classes((CSVRenderer,))
def download_csv_file(request, format=None):
mymodel_id = request.query_params.get('mymodel_id', None)
print 'format', format
csv_file = MyModel.objects.get(id=mymodel_id)
serializer = MyModelSerializer(csv_file)
return Response(serializer.data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment