我正在关注此帖Python get file name and change & save it in variable,并进行了一些更改,可以在此帖Python get file name and change & save it in variable中看到。
我的任务是在HTML页面中手动显示这个已更改的.txt文件(在list.html中插入文件的路径)或动态地(将'newfilename'传递给list.html)。
太困惑了,如何在html上提供下载选项。 两个文件都在同一个文件夹中。 请建议
# -*- coding: utf-8 -*-
import sqlite3
import csv
import sys
import os
import xlsxwriter
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from myproject.myapp.models import Document
from myproject.myapp.forms import DocumentForm
def list(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
docfile = request.FILES['docfile']
filename = os.path.splitext(docfile.name)[0]
newfilename= 'ok_%s.xlsx' %filename
gfile= csv.reader(request.FILES['docfile'])
gon = sqlite3.connect('../myproject/database/database.sqlite3')
gon.text_factory = str
gon.execute("DELETE FROM test where rowID > 0 ")
gon.executemany('insert into test values (?, ?, ?)', gfile)
gon.commit()
gon.close()
conn=sqlite3.connect('../myproject/database/database.sqlite3')
conn.text_factory = str
c=conn.cursor()
ion=c.execute("delete from test where [Manager id] = 'local'")
.....
.....
conn.commit()
conn.close()
workbook = xlsxwriter.Workbook('../myproject/media/documents/'+newfilename)
worksheet = workbook.add_worksheet("no emp")
worksheet2 = workbook.add_worksheet("Manager id")
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
#documents = Document.objects.all().delete()
#documents = Document.objects.all()
#mocuments = '../myproject/media/documents/ok_2.xlsx' #this is what i am trying to do
# Render list page with the documents and the form
documents = Document.objects.all()
return render_to_response(
'myapp/list.html', {'documents': documents, 'form': form}, context_instance=RequestContext(request)
)
答案 0 :(得分:0)
您应修改list.html
模板,如下所示:
<ul>
{% for document in documents %}
<li>
<a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a>
</li>
{% endfor %}
</ul>
这假设Document.docfile
是models.FileField。