我想通过搜索和替换所需单词来编辑网页上所需的上传文件。如何获取该文档文件的文本?
我的模型中有一个文件字段,我的文档文件在网页列表中,可以删除所需的文件或上传新文件。我尝试通过在views.py中创建一个函数来编辑所需的上载doc文件。我尝试使用docx模块打开上载的文件,还尝试了io.StringIO(),但没有设法获得所需的输出。
class DocFile(models.Model):
title = models.CharField(max_length=50)
agreement = models.FileField(upload_to='')
def edit_file(request, upload_id):
instance = get_object_or_404(DocFile, id=upload_id)
content = instance.agreement.open(mode='rb')
variables = []
for line in content:
match = re.findall(r"\{(.*?)\}", line.text)
variables.append(match)
return render(request, 'uploads/file_detail.html', {
'variables': variables
})
或
def edit_file(request, upload_id):
instance = get_object_or_404(DocFile, id=upload_id)
content = instance.agreement(upload_id)
with open(content, 'rb') as f:
instance.agreement = File(f)
source = io.StringIO(f)
document = Document(source)
variables = []
for paragraph in document.paragraphs:
match = re.findall(r"\{(.*?)\}", paragraph.text)
variables.append(match)
for table in document.tables:
for row in table.rows:
for cell in row.cells:
match = re.findall(r"\{(.*?)\}", cell.text)
variables.append(match)
source.close()
target = io.StringIO()
document.save(target)
return render(request, 'uploads/file_detail.html', {
'variables': variables
})
{% block content %}
<form method="post">
{% csrf_token %}
{% if variables %}
{% for variable in variables %}
{% for var in variable %}
{{ var }} <br /><input type="text", name="statement">
<br />
<br />
{% endfor %}
{% endfor %}
<input type="submit" value="Download">
{% endif %}
</form>
<a href="{{ template.agreement }}" class="btn btn-primary btn-sm">
Edit
</a>
{% endblock %}
运行第一个视图函数时,出现以下错误:
AttributeError at /template/11/
'bytes' object has no attribute 'text'
当我运行第二个视图函数方法时,出现以下错误:
TypeError at /template/11/
'FieldFile' object is not callable