Django: Разбор docx и получение содержимого из документа

Я пишу Django приложение, в котором пользователь может загрузить .docx файл и получить флеш-карты, сделанные в db из разобранного документа.

Флешкарты создаются из различных типов заголовков, как показано ниже:

Заголовок: Категория флэшкарт, Заголовок 1: Название флеш-карты, Заголовок нормальный: Содержание флешкарты

Проблема в том, что когда я загружаю документ word. Категория создается, но заголовок и содержание - пустые строки...

Я сделал отдельный файл python с тем же func и там все работает: категория, заголовок и содержание точно такие, как должны быть.

Вход одинаковый в обоих случаях (файл Flask.docx):

Flask Framework             (using heading Title, so it should be the category)
Flask                       (using Heading 1, so it should be the title of a flashcard)
Is a Python Web framework.  (using heading normal, so it should be the content of a flashcard)

Django:

  • Модели:
from django.db import models

# Create your models here.


class FlashcardCategory(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=30, unique=True, help_text="Category of flashcards.")

    def __str__(self):
        return self.name


class Flashcard(models.Model):
    id = models.IntegerField(primary_key=True)
    category = models.ForeignKey(FlashcardCategory, on_delete=models.CASCADE)
    title = models.CharField(max_length=50, help_text="Title of flashcard.")
    content = models.TextField(unique=True, help_text="Content (reverse) of flashcard.")

    def __str__(self):
        return f"{self.title} - {self.content}"

  • Вид:
def upload_documents_and_parse(request):
    """
    Function based view where user can upload his/hers document (only .docx).
    Then app is going to try to parse the document and create flashcards.
    If something goes wrong, app is going to inform user.
    """
    if request.method == "POST":
        form = WordDocumentForm(request.POST, request.FILES)
        if form.is_valid():
            uploaded_document = request.FILES['document']
            document_to_parse = Document(uploaded_document)
            category = str()
            title = str()
            content = str()
            for paragraph in document_to_parse.paragraphs:
                if paragraph.style.name == "normal":
                    content = paragraph.text
                elif paragraph.style.name == "Heading 1":
                    title = paragraph.text
                elif paragraph.style.name == 'Title':
                    category = paragraph.text
                flashcard_category_instance = FlashcardCategory(name=category)
                flashcard_category_instance.save()
                flashcard_instance = Flashcard(category=FlashcardCategory.objects.get(name=category),
                                               title=title,
                                               content=content)
                flashcard_instance.save()
                return HttpResponse(f"Category: {category}, title: {title}, content: {content}")
            return redirect('home_page')
        else:
            HttpResponse("Something went wrong. Try again.")
    else:
        form = WordDocumentForm()
    return render(request, "upload_and_parse.html", {"form": form})

Выход этого представления django (после загрузки файла):

  • Категория: Flask Framework,
  • Заголовок:
  • Содержание:

Простая функция Python (вне проекта Django):

from docx import Document


def parser(path):
    docs = Document(path)
    title = str()
    heading = str()
    text = str()
    for paragraph in docs.paragraphs:
        if paragraph.style.name == 'Title':
            title = paragraph.text
        elif paragraph.style.name == "Heading 1":
            heading = paragraph.text
        elif paragraph.style.name == "normal":
            text = paragraph.text
    return f"Title: {title}\nHeading: {heading}\nTitle: {text}"

И вывод из этой функции (что правильно, и Django должен делать то же самое и сохранять это в db):

  • Название: Flask Framework
  • Глава: Flask
  • Заголовок: Это веб-фреймворк на языке Python.

Может ли кто-нибудь помочь?

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