现在添加一个对图书信息CSV文件的导入导出操作
1. 新建“forms”
右键项目名称,新建包“file”。
右键包名“file”,新建“forms.py”, 代码如下:
#!usr/bin/env python
#coding: utf-8
'''
Created on 2012-7-11
@author: jingwen.wu
'''
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
2. 添加导入导出操作
在“library/book/views.py”里添加代码:
def uploadfile(request):
if request.POST:
form = UploadFileForm(request.POST, request.FILES)
f = request.FILES['file']
line = f.readline() #读取表头
while True:
line = f.readline()
try:
line1 = line.decode('utf-8-sig')
if not line1 or line1 == '\r\n' or line1 =='\r' or line1 == '\n' or line1 == '': break
arg = line1.split(',')
publicationTime = arg[3].rstrip('\r\n')
book = Book(name = arg[0], author = arg[2], press = arg[1], publicationTime = publicationTime)
book.save()
except:
pass
line2 = line.decode('gb2312')
if not line2 or line2 == '\r\n' or line2 =='\r' or line2 == '\n' or line2 == '': break
arg = line2.split(',')
publicationTime = arg[3].rstrip('\r\n')
book = Book(name = arg[0], author = arg[2], press = arg[1], publicationTime = publicationTime)
book.save()
f.close()
return render_to_response('book/success.html')
else:
form = UploadFileForm()
return render_to_response('book/upload.html', {'form': form}, context_instance=RequestContext(request))
def downloadfile(request):
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=book_list.csv'
writer = csv.writer(response)
writer.writerow(['name', 'author', 'press', 'publicationTime', 'reader'])
books = Book.objects.all()
for book in books:
if book.reader_id:
try :
readName = Reader.objects.get(id__iexact = book.reader_id).name
except:
readName = ''
else :
readName = ''
writer.writerow([book.name, book.author, book.press, book.publicationTime, readName])
return response
3. 修改“urls.py”
在“library/book/urls.py”的“patterns()”里添加如下代码:
url(r'^upload/$', 'book.views.uploadfile', name = "books_uploadfile"),
url(r'^download/$', 'book.views.downloadfile', name = "books_downloadfile"),
4. 添加导入文件模板
在“library/static/static/template”下添加导入文件模板“book_list.csv”
5. 添加导入界面
在“library/templates/book”下添加“upload.html”,代码如下:
由于回带方法“οnsubmit="return iframeCallback(this, dialogAjaxDone)"”(具体什么原因现在也没搞清楚……),导入成功后的提示信息不能像之前一样在“views.py”添加“return HttpResponse(simplejson.dumps({"statusCode":200, "navTabId":request.POST.get('navTabId', 'bookindex'), "callbackType":request.POST.get('callbackType', None), "message":u'删除成功', "info":u'删除成功', "result":u'删除成功'}), mimetype='application/json')”显示提示信息,而是通过“success.html”显示,显示效果一样。
在“library/templates/book”下添加“success.html”,代码如下:
{
"statusCode":"200",
"message":"\u64cd\u4f5c\u6210\u529f",
"navTabId":"bookindex",
"rel":"",
"callbackType":"closeCurrent",
"forwardUrl":"",
"confirmMsg":""
}
5. 在图书主页面添加导入导出按钮
在“library/templates/book/basepage.html”的“toolBar”中添加如下代码:
line
导入CSV文件
导出CSV文件
6. 运行
图书管理主界面
导入文件界面