在Django中,我希望能够上传.zip文件。该zip文件包含我要阅读和处理的scl文件(基本上是纯文本)。我要保存在本地的.zip和.scl。
问题是我无法通过upload_to方法将本地提取的.scl文件保存到模型中。在上传.zip和提取scl文件后,它会出现在项目的根目录中。我当前的解决方案如下,此处提取了zip,然后将其移动,但是这些路径是硬编码的,如果两个文件具有相同的名称,则会引发错误。如果找到了相似的命名文件,upload_to方法将重命名文件,并将重命名的文件路径保存到数据库。
models.py
class Default_software(models.Model):
version = models.CharField(max_length=10, help_text='AISA_V2-Q')
zip_location = models.FileField(upload_to='default_software') #docfile
scl_location = models.FileField(upload_to='default_scl')
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
"""String for representing the Model object"""
return self.name
views.py
from django.views.decorators.csrf import csrf_exempt
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.urls import reverse
from myapp.models import Default_software
from myapp.forms import DocumentForm
# import aboslute URL for files processing
from django.conf import settings
# file handling and saving
from shutil import move
# creating django file objects
from django.core.files import File
# zipprocessing
import zipfile
@csrf_exempt
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
print(request.FILES)
process_file(request.FILES['docfile'])
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('list'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
software_list = Default_software.objects.all()
# Render list page with the documents and the form
return render(request, 'list.html', {'default_software_list': software_list, 'form': form})
def process_file(upload):
zip = zipfile.ZipFile(upload)
# extract zip and search for .scl file
zip_contents = zip.namelist()
scl = zip.extract(zip_contents[0]) # scl file
print("scl type: ", type(scl))
with open(scl) as f:
for line in f:
pass
#print(line)
# move scl file to correct directory
move('test.SCL', 'media/default_scl')
# Save all to database
#newdoc = Default_software(zip_location=upload, scl_location='default_scl/test.SCL', version='dunno')
newdoc.save() # save all contents
list.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Minimal Django File Upload Example</title>
</head>
<body>
<!-- List of uploaded documents -->
{% if default_software_list %}
<ul>
{% for default in default_software_list %}
<li><a href="{{ default.zip_location.url }}">{{ default.zip_location.name }}</a>- {{ default.created_at }}</li>
{% endfor %}
</ul>
{% else %}
<p>No default software uploaded...</p>
{% endif %}
<!-- Upload form. Note enctype attribute! -->
<form action="{% url "list" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload"/></p>
</form>
</body>
</html>
zip保存到/ root_project / media / default_software
scl保存到/ root_project / media / default_scl
最后,我如何处理Django将提取的zip文件从文件根移动到模型指定路径中的压缩文件?