如何将python-doc对象保存到DRF模型

时间:2018-12-19 22:04:13

标签: python django django-rest-framework python-docx

我有一个 Django Rest Framework 视图,该视图生成 python-docx 对象,并且我想将这些文件保存在模型中。我在 python-docx 文档中读到,您可以指定一个“文件状”对象来保存该对象,但是我不明白它的含义。

这是我的观点:

class RoomingWordView(viewsets.ViewSet):
    def list(self, request, *args, **kwargs):
        ... some code
        documents_to_return = self.get_hotel_document(start_date, end_date, confirmed, hotel, bookings)
        return Response(documents_to_return)

    def get_hotel_document(self, start_date, end_date, confirmed, hotel, bookings):
        from django.core.files import File
        from docx import Document
        from docx.shared import Inches, Pt

        document = Document()

        section = document.sections[-1]
        section.left_margin = Inches(0.5)
        section.right_margin = Inches(0.5)

        style = document.styles['Normal']
        font = style.font
        font.name ='Arial'
        font.size = Pt(10)

        document.add_heading("MY COMPANY")
        if confirmed:
            document.add_paragraph("ROOMING LIST DEL 01-12-2018 AL 31-01-2019 INCLUYE RESERVAS CONFIRMADAS")
        else:
            document.add_paragraph("ROOMING LIST DEL 01-12-2018 AL 31-01-2019")
        document.add_paragraph("Hotel: {}".format(hotel))

        table = document.add_table(rows=len(bookings), cols=10)
        hdr_cells = table.rows[0].cells
        hdr_cells[0].text = 'Booking'
        hdr_cells[1].text = 'Reservado a'
        hdr_cells[2].text = '# Pax'
        hdr_cells[3].text = 'Agencia'
        hdr_cells[4].text = 'Habs'
        hdr_cells[5].text = 'Hab./Plan'
        hdr_cells[6].text = 'Entrada'
        hdr_cells[7].text = 'Salida'
        hdr_cells[8].text = 'Confirmación'
        hdr_cells[9].text = 'Producción'

        for cell in table.rows[0].cells:
            paragraphs = cell.paragraphs
            for paragraph in paragraphs:
                for run in paragraph.runs:
                    run.underline = True

        for booking in bookings['bookings']:
            row_cells = table.add_row().cells
            row_cells[0].text = booking['booking']
            row_cells[1].text = "\n".join(booking['people'])
            row_cells[2].text = booking['pax']
            row_cells[3].text = booking['agency']
            row_cells[4].text = booking['rooms']
            row_cells[5].text = "{}\n{}".format(booking['room_type'], booking['plan_type'])
            row_cells[6].text = booking['check_in']
            row_cells[7].text = booking['check_out']
            row_cells[8].text = booking['confirmation']
            row_cells[9].text = str(booking['production'])

        for row in table.rows:
            for cell in row.cells:
                paragraphs = cell.paragraphs
                for paragraph in paragraphs:
                    for run in paragraph.runs:
                        font = run.font
                        font.size = Pt(8)

        file_object = "rooming_reports/Rooming {} {}-{}.docx".format(hotel, start_date, end_date)
        document.save(file_object)

        return file_object

我希望视图将生成的 document 对象保存在名为RoomingWordDocument的模型中,而不是将其保存为文件,但是我不知道如何分配{{1 }}变量添加到document字段。

1 个答案:

答案 0 :(得分:1)

假设您有一个模型

class RoomingWordDocument(models.Model):
    doc = models.FileField(null=True)
    name = models.CharField(max_length=50)

然后尝试此代码段

class RoomingWordView(viewsets.ViewSet):
    def list(self, request, *args, **kwargs):

    # your list method
    # return Response(documents_to_return)

    def get_hotel_document(self, start_date, end_date, confirmed, hotel, bookings):
        # your code
        # ......

        file_object = "rooming_reports/Rooming {} {}-{}.docx".format(hotel, start_date, end_date)
        document.save(file_object)

        # here is the new snippet
        # found a simple way now
        model_object = RoomingWordDocument.objects.create(name="somename")
        model_object.doc.name = file_object
        model_object.save() # this is importent

        try:
            from StringIO import StringIO
        except ImportError:
            from io import StringIO
        from django.core.files import File

        fp = open(file_object, 'rb')
        model_object = RoomingWordDocument.objects.create(name="somename")
        model_object.doc.save(file_object, File(fp))

        return Response("some response")

参考
1. StringIo in Python2.X and 3.X
2. How to create a file and save it to a model's FileField?
3. Set Django's FileField to an existing file