1

我正在关注这篇文章Python 获取文件名并更改并保存在变量中,并进行了一些更改,这些更改可以在这篇文章中看到Python 获取文件名并更改并保存在变量中

我的任务是手动(在list.html 中插入文件的路径)或动态(传递'newfilename')在HTML 页面中显示这个更改的.txt 文件给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)
    )
4

1 回答 1

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

于 2013-09-22T19:39:45.430 回答