Django不会更改文件名

Django不会更改文件名

本文介绍了HttpResponse Django不会更改文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循了3个答案:






我的 POSTMAN 是v4.10.3

My POSTMAN is v4.10.3

class SBrandJobRawDataView(APIView):
    permission_classes = []
    authentication_classes = (TokenAuthentication,)

    def get(self, request, format=None):
        data = {
            "message": _("GET method is not allowed"),
        }
        return Response(data=data, status=status.HTTP_400_BAD_REQUEST, )

    def post(self, request, format=None):
        from_date = request.data.get('from_date')
        to_date = request.data.get('to_date')
        queryset = get_raw_sbrand_record(from_date, to_date)
        filename = f"From_{from_date.get('year')}-{from_date.get('month')}-{from_date.get('day')}_to_" \
                   f"{to_date.get('year')}-{to_date.get('month')}-{to_date.get('day')}.xlsx"
        # Allow only last file stay in the server.
        clean_dir("xlsx")

        # Create Excel report
        gen_sbrand_report(queryset, filename)

        # Open file
        abs_file = os.getcwd() + '/' + filename
        xls_file = open(abs_file, 'rb')

        # Response with attachment
        response = HttpResponse(xls_file,
                            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        response['Content-Disposition'] = f"attachment; filename={filename}"
        import pdb; pdb.set_trace()
        return response

我知道我正在混合 Django Django REST 响应。如果我使用rest_framework.response import响应中的 我会收到错误

I am aware that I am mixing Django and Django REST response. If I use from rest_framework.response import Response I get error

Internal Server Error: /api/sbrand-jobs/reports
Traceback (most recent call last):
  File "/Users/el/.pyenv/versions/siam-sbrand/lib/python3.6/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = get_response(request)
  File "/Users/el/.pyenv/versions/siam-sbrand/lib/python3.6/site-packages/django/core/handlers/base.py", line 217, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/el/.pyenv/versions/siam-sbrand/lib/python3.6/site-packages/django/core/handlers/base.py", line 215, in _get_response
    response = response.render()
  File "/Users/el/.pyenv/versions/siam-sbrand/lib/python3.6/site-packages/django/template/response.py", line 109, in render
    self.content = self.rendered_content
  File "/Users/el/.pyenv/versions/siam-sbrand/lib/python3.6/site-packages/rest_framework/response.py", line 72, in rendered_content
    ret = renderer.render(self.data, accepted_media_type, context)
  File "/Users/el/.pyenv/versions/siam-sbrand/lib/python3.6/site-packages/rest_framework/renderers.py", line 103, in render
    separators=separators
  File "/Users/el/.pyenv/versions/3.6.0/lib/python3.6/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/Users/el/.pyenv/versions/3.6.0/lib/python3.6/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/Users/el/.pyenv/versions/3.6.0/lib/python3.6/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/Users/el/.pyenv/versions/siam-sbrand/lib/python3.6/site-packages/rest_framework/utils/encoders.py", line 54, in default
    return obj.decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x94 in position 15: invalid start byte
"POST /api/sbrand-jobs/reports HTTP/1.1" 500 103626

这是调试行

(Pdb) response['Content-Disposition']
'attachment; filename=From_2017-1-1_to_2017-12-25.xlsx'

问题:

我得到了 response.xlsx 不是我的分配名称。

Problem:
I got response.xlsx not my assigned name.

推荐答案

尝试一下:

from django.utils.http import urlquote
response['Content-Disposition'] = 'attachment; filename={}'.format(urlquote(filename))

这篇关于HttpResponse Django不会更改文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 13:19