Загрузить файл, созданный с помощью python-docx из Django DRF?

Я пытаюсь создать файл с помощью python-docx и download создать его с помощью DRF/Django.

Я перепробовал почти все ответы на вопросы, похожие на мой. Я получаю ошибки

Api.py

class CreateDocx(viewsets.ModelViewSet):
    queryset = BooksModel.objects.all()
    serializer_class = BooksSerializer
    # serializer_class = BooksSerializer
    # permission_classes = [
    #     permissions.AllowAny
    # ]
    # def get(self):
    def download(self, request):
        print('creating file')
        document = file_create() # Function is returning a Document from python-docx, see below
        response = FileResponse(document, content_type='application/msword')
        # response['Content-Length'] = instance.file.size
        response['Content-Disposition'] = 'attachment; filename="TEST.docx"'
        return response

 

file_create функция:

def file_create():
    document = Document()
    docx_title = "TEST_DOCUMENT.docx"
    # Get the required info
    queryset = BooksModel.objects.all()
    # Place queries in document
    for query in queryset.values():
        print(query)
        table = document.add_table(rows=1, cols=1)
        pic_cel = table.rows[0].cells[0].paragraphs[0]
        run = pic_cel.add_run()
        run.add_picture("/Users/xxx/Downloads/1.jpg", width=Mm(90), height=Mm(45))
                print('added picture')
    return document

urls.py

from rest_framework import routers
from .api import CreateDocx

router = routers.DefaultRouter()
router.register('api/download', CreateDocx, 'download-doc')


urlpatterns = router.urls

Когда я делаю вызов api/download/, я получаю ответ json. Я не могу понять, что я делаю неправильно, потому что кажется, что функция download внутри CreateDocx не вызывается вообще. Я пробовал удалять serializer_class и queryset перед функцией, но это приводит к ошибкам. Например:

' CreateDocx' должен либо включать атрибут queryset, либо переопределять метод get_queryset(). Или 'CreateDocx' должен либо включать атрибут serializer_class, либо переопределять метод get_serializer_class().

Вернуться на верх