如果POST(在Django管理页面中)文件的扩展名为.doc
,我想将.docx
转换为.doc
。
当POSTED文件扩展为.docx
时,不会发生任何错误:Django将document.docx
上传到media/documents/document.docx
中,我可以读取它。
但是,如果POST文件具有.doc
扩展名,那么我会有奇怪的Django行为:它不会将document.doc
上传到media/documents/document.doc
中!代替此Django,请为该文件创建诸如document.doc ('documents/document.docx' for the .docx file)
之类的关系路径,并且完整路径也是错误的:/home/steppenhorde/project/app/media/document.doc (/home/steppenhorde/project/app/media/documents/document.docx for the .docx file)
。
因此我得到了一个类似“ /home/steppenhorde/project/app/media/documents/document.docx
找不到包裹
# MEDIA_ROOT = os.path.join(BASE_DIR, 'media') in the settings.py
# file = models.FileField(upload_to='documents/') in the models.py
# filepath = Model.file
if filepath.path.endswith('.doc'):
doc_filepath = filepath
print(doc_filepath) # document.doc
print(doc_filepath.path) # /home/steppenhorde/project/app/media/document.doc
os.system(f'antiword {doc_filepath} > {docx_filepath}') # after this I have some code for parse docx_filepath
else:
docx_filepath = filepath
print(docx_filepath) # documents/document.docx
print(docx_filepath.path) # /home/steppenhorde/project/app/media/documents/document.docx
我试图像这样自己走自己的路
doc_filepath = filepath
splitted_doc_filepath = doc_filepath.path.split('/')
doc_file_name = splitted_doc_filepath[-1]
docx_filepath = f'{MEDIA_ROOT}/documents/{doc_file_name}x'
但是我仍然得到一个例外,例如“在'/home/steppenhorde/project/app/media/documents/document.docx'找不到软件包”,因为Django不会将document.doc上传到media / documents / document .doc