functionality. ? ? p.drawString(100, 100, "Hello world.")? ? # Close the PDF object cleanly. ? ? p.showPage() ? ? p.save()
? ? # Get the value of the StringIO buffer and write it to the response. ? ? response.write(temp.getvalue()) ? ? return response
其他可能的格式 实质上,任何可以写文件的Python库都可与Django的HttpResponse结合用以返回特定格式的内容,如ZIP文件、动态图片、图表、XLS文件等等。
最后在看一个返回xls文件的例子
from django.http import HttpResponse import xlwt def viewXls(request): ? ? response = HttpResponse(mimetype='application/vnd.ms-excel')? ? ? response['Content-Disposition'] = 'attachment; filename=request.xls'? ? ? ? book = xlwt.Workbook(encoding='utf8')? ? ? sheet = book.add_sheet('untitled') ? ? for row, column, value in ((0,0,1),(0,1,2),(1,0,3),(1,1,4)) ? ? sheet.write(int(row),int(column),value) ? ? book.save(response) ? ? return response
流程同上,不在注释。
另外,需要特别注意的是,这里的request必须是通过表单提交才能正确返回特定格式的内容,若要是通过ajax方式发起的request则返回的内容会被当做文本串处理,而不能被浏览器解释为特定内容。 比如:
$.ajax({ ? ? ? ? ? ? ? ? url:"{% url 'mycitsm.views.viewXls' %}", ? ? ? ? ? ? ? ? data:postData, ? ? ? ? ? ? ? ? type:"POST", ? ? ? ? ? ? ? ? success:function(result){
? ? ? ? ? ? ? ? }, ? ? ? }); //是不可以的,而要使用如下的表单提交才可以: var form = $("#xlsForm"); form.attr({ ?action:"{% url 'mycitsm.views.returnXls' %}", ?method:"POST"? ? ? ? }); form.submit();
说到这里有必要记录一下开发过程中遇到的一个问题,也即将表单内容序列化为字符串的问题。 有时需将表单中的所有内容序列化为键值对构成的串做为一个整体进行URL参数传递,而且需要对值中包含的特殊字符进行编码。比如有如下表单:
$('form').submit(function() {
? alert($(this).serialize());
? return false;
}); #可以输出 a=1&c=3&d=4&e=5
为什么第二个text类型的input的值还有checkbox类型的input的值以及submit类型的input没有被序列化呢?这是因为如果要表单元素的值包含到序列字符串中,元素必须使用 name 属性。而第二个text类型的input无name属性。checkbox类型的input有一个并没有被checked所以……。serialize()只会将”成功的控件“序列化为字符串。如果不使用按钮来提交表单,则不对提交按钮的值序列化,所以submit类型的input没有被序列化。 当然除了直接对整个form序列化外还可对已选取的个别表单元素的jQuery对象序列化,如 ,等等。