Как я могу получить фактический путь к файлу docx, загруженному в базу данных, используя модели django?
Я разрабатываю простое веб-приложение с использованием django, которое может принимать три .docx файла, содержащих таблицы, объединять эти таблицы в один файл и возвращать этот файл пользователю в загружаемой форме. Я использовал библиотеку python-docx для обработки файлов docx. Все три файла успешно загружаются без каких-либо проблем, но проблема возникает, когда я пытаюсь открыть эти файлы документов с помощью конструктора doc.Document(file path)
библиотеки docx. Но проблема в том, что doc.Document() не может открыть файл word и выдает ошибку типа docx.opc.exceptions.PackageNotFoundError: Package not found at '/media/documents/word/SS_SMS39_CE3_InQfp7c.docx'
, в то время как он четко показывает путь и при проверке на /media/documents... я могу четко найти этот файл. Я много пытался найти информацию по этому вопросу, просмотрел документацию по docx и даже документацию по файловому хранилищу django. Но я не могу решить эту проблему. Если вы можете помочь мне решить эту проблему, я буду благодарен. Я предоставил все models.py, views.py, urls.py и мои шаблоны
models.py
from django.db import models
class Mydocument(models.Model):
file1 = models.FileField(upload_to='documents/word/')
file2 = models.FileField(upload_to='documents/word/')
file3 = models.FileField(upload_to='documents/word/')
file_processed = models.FileField(upload_to='documents/word/',null=True,default='documents/word/ssm.docx')
views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .forms import DocumentForm
from .models import Mydocument
import docx as dc
def SS_Merge(response, n, f1,f2,f3):
file = Mydocument.objects.get(id=n)
merged_url = file.file_processed.url
print(merged_url)
#doc = dc.Document(merged_url)
doc1 = dc.Document(f1)
doc2 = dc.Document(f2)
doc3 = dc.Document(f3)
##Some Code for performing all the file processing logic and Merging them.
doc.save('ss merged.docx')
#Trying to update the file at database with the new one"
return render(response, 'download.html', {'file': file})
def home(response):
if response.method == 'POST':
form = DocumentForm(response.POST, response.FILES)
if form.is_valid():
new_doc= form.save()
file1_name = new_doc.file1.url
file2_name = new_doc.file2.url
file3_name = new_doc.file3.url
number =new_doc.pk
print(number)
print("url",file2_name)
print("url",file1_name)
SS_Merge(response,number,file1_name,file2_name,file3_name)
#return redirect('home')
print("Sucessful Fileupload")
#return render(response, 'download.html', {'form': form})
else:
form = DocumentForm()
return render(response,'upload.html',{'form':form})
urls.py
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('myapp/',include('myapp.urls') ),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
urlpatterns +=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
Settings.py
#Other Things
TATIC_URL = 'static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'myapp/static/')
]
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
upload.html
{% extends 'base.html' %}
{% block content %}
<h2> Upload Three SS Files Here..</h2>
<br/>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="input-group mb-3">
<input type="file" class="form-control" id="inputGroupFile01" name="file1">
<label class="input-group-text" for="inputGroupFile02">Upload</label>
</div>
<br/>
<div class="input-group mb-3">
<input type="file" class="form-control" id="inputGroupFile03" name="file2">
<label class="input-group-text" for="inputGroupFile02">Upload</label>
</div>
<br/>
<div class="input-group mb-3">
<input type="file" class="form-control" id="inputGroupFile02" name="file3">
<label class="input-group-text" for="inputGroupFile02">Upload</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
<h5> Hit Merge to merge all three files</h5>
{% endblock %}
download.html
{% extends 'base.html' %}
{% block content %}
<h1> SS-Merge Successful!!</h1>
<br/>
<h2> Click Download to Get your Merged SS</h2>
<br/>
<a href="{{ file.file_processed.url }}" class = "btn btn-secondary btn-sm" target="_blank"> Download Docx</a>
<br/>
</div>
</form>
{% endblock %}