


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.
Example:
Generate content in CSV format
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:
1. The mimetype specified in HttpResponse is 'text/csv' The document returned by the browser is a CSV file.
2.HttpResponse sets another parameter Content-Disposition, where attachment tells the browser to save the returned document instead of displaying its content. filename specifies the name of the returned document. The name can be specified arbitrarily.
3. Because the writer method of csv expects a file type object as a parameter, and the HttpResponse instance can be used as a file, you can directly use HttpResponse as a parameter in the writer method of the csv module.
4. The writer.writerow method is responsible for writing a line of content to the file.
The above method is a general pattern for returning content in non-HTML format, that is, creating an HttpResponse of a specific MIME Type, passing it to a method that takes a file as a parameter to generate a document in a specific format, and then returning the response.
Generate content in PDF format
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:
1. The application/pdf MIME type is used here Tell the browser that the returned PDF file is not HTML, otherwise the browser will treat it as ordinary HTML content.
2. The canvas.Canvas method expects a file-like object as a parameter, passing HttpResponse to the method.
3. Use the method of the Canvas instance to draw the PDF document and call the showPage() method and save() method (otherwise a damaged PDF document will be generated).
4. Finally return the HttpResponse instance
to generate a more complex PDF document. The cStringIO library is used here to temporarily store the PDF file
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
Essentially, any Python library that can write files can be combined with Django's HttpResponse to return content in a specific format, such as ZIP files, dynamic images, charts, XLS files, etc.
Finally, let’s look at an example of returning an xls file
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.
In addition, it is important to note that the request here must be submitted through a form to correctly return content in a specific format. If the request is initiated through Ajax, the returned content will be treated as a text string. Cannot be interpreted by the browser as specific content.
For example:
$.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.
Sometimes it is necessary to serialize all the content in the form into a string of key-value pairs and pass the URL parameters as a whole, and the special characters contained in the value need to be encoded. For example, there is the following 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.
Of course, in addition to directly serializing the entire form, you can also serialize jQuery objects of selected individual form elements, such as ,

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

HTMLisaspecifictypeofcodefocusedonstructuringwebcontent,while"code"broadlyincludeslanguageslikeJavaScriptandPythonforfunctionality.1)HTMLdefineswebpagestructureusingtags.2)"Code"encompassesawiderrangeoflanguagesforlogicandinteract

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

How to design the dotted line segmentation effect in the menu? When designing menus, it is usually not difficult to align left and right between the dish name and price, but how about the dotted line or point in the middle...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version