Home >Web Front-end >HTML Tutorial >How to generate content in non-HTML format in Django. _html/css_WEB-ITnose
Sometimes there may be a need to click a link or a button on a web page to return a picture, a pdf document, a csv document, etc. instead of HTML. It's easy to do this in diango. Views in Django are used to receive http requests and return web responses. Normally, the content returned is HTML, but it can return more than just that, it can also be the above pictures, PDF files, etc. The key to returning non-HTML content lies in the HttpResponse class, especially the mimetype parameter. By setting this parameter to different values, you can prompt the browser view to return content in different formats. For example, if you want to return the image content, you only need to read an image, then specify the mimetype of the image in the HttpResponse and respond to the image content as another parameter to the browser, and the browser can automatically and correctly display the image content.
from django.http import HttpResponsedef my_image(request): image_data = open("/path/to/my/image.png", "rb").read() return HttpResponse(image_data, mimetype="image/png")Another thing that needs special attention is that the HttpResponse object implements Python's standard "file-like-object" API, that is, you can use HttpResponse as a file.
import csvfrom django.http import HttpResponse# Number of unruly passengers each year 1995 - 2005. In a real application# this would likely come from a database or some other back-end data store.UNRULY_PASSENGERS = [146,184,235,200,226,251,299,273,281,304,203]def unruly_passengers_csv(request): # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=unruly.csv' # Create the CSV writer using the HttpResponse as the "file." writer = csv.writer(response) writer.writerow(['Year', 'Unruly Airline Passengers']) for (year, num) in zip(range(1995, 2006), UNRULY_PASSENGERS): writer.writerow([year, num]) return responseA few points to note:
from reportlab.pdfgen import canvasfrom django.http import HttpResponsedef hello_pdf(request): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=hello.pdf' # Create the PDF object, using the response object as its "file." p = canvas.Canvas(response) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 100, "Hello world.") # Close the PDF object cleanly, and we're done. p.showPage() p.save() return responseThe process is basically the same as above, with a few points to note:
from cStringIO import StringIOfrom reportlab.pdfgen import canvasfrom django.http import HttpResponsedef hello_pdf(request): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=hello.pdf' temp = StringIO() # Create the PDF object, using the StringIO object as its "file." p = canvas.Canvas(temp) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of 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 responseOthers Possible formats
from django.http import HttpResponseimport xlwtdef 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 responseThe process is the same as above, without comments.
$.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();Speaking of which, it is necessary to record a problem encountered during the development process, which is the problem of serializing form content into strings.
<form> <div><input type="text" name="a" value="1" id="a" /></div> <div><input type="text" value="2" id="b" /></div> <div><input type="hidden" name="c" value="3" id="c" /></div> <div> <textarea name="d" rows="8" cols="40">4</textarea> </div> <div><select name="e"> <option value="5" selected="selected">5</option> <option value="6">6</option> <option value="7">7</option> </select></div> <div> <input type="checkbox" name="f" value="8" id="f" /> </div> <div> <input type="submit" name="g" value="Submit" id="g" /> </div></form>$('form').submit(function() { alert($(this).serialize()); return false;});#可以输出a=1&c=3&d=4&e=5Why are the values of the second text type input, the checkbox type input value and the submit type input not serialized? This is because if a form element's value is to be included in a sequence string, the element must use a name attribute. The second text type input has no name attribute. One of the checkbox type inputs is not checked, so... serialize() will only serialize "successful controls" into strings. If you do not use a button to submit the form, the value of the submit button is not serialized, so the submit type input is not serialized.