我需要将docx文件中的数据插入我的sqlite数据库中

时间:2019-06-02 15:24:40

标签: python django docx

我需要将数据(文本)从docx文件导入到我的sqlite数据库中。

我在我的models.py中有此代码,但是不起作用。 任何想法

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
import docx2txt
# Create your models here.


class Post(models.Model):
    title = models.CharField(max_length=60)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    time_read = models.IntegerField(default=3)
    category = models.CharField(max_length=40)
    email = models.EmailField(User.get_email_field_name(),default='xxxxxxxxxxxxxx')

def __str__(self):
    return self.title

def get_post(self):
    txt = docx2txt.process("/home/master/Downloads/test1.docx")
    post = Post
    post.title = txt.readline()
    post.author = "master"
    post.category = txt.readline()
    post.content = txt.readlines()
    post.save()

2 个答案:

答案 0 :(得分:0)

post = Post ....不应该是post = Post()... ???

post =Post(title = txt.readline(), author = "master", category = txt.readline(), content = txt.readlines())
post.save()

很难说出没有错误消息。

答案 1 :(得分:0)

好的,我设法: 它是:

def get_post(self):
txt = docx2txt.process("/home/master/Downloads/test1.docx")
post = Post.objects.create()
post.title = txt.readline()
post.author = "master"
post.category = txt.readline()
post.content = txt.readlines()
post.save()

谢谢杰伊和亚当