How to generate non-HTML content in django ., Django

Source: Internet
Author: User

How to generate non-HTML content in django ., Django

In some cases, you may need to click a link or button on the webpage to return an image, a pdf file, a csv file, and so on, rather than HTML. It is easy to do this in diango. View in django is used to receive http requests and return web response. Normally, the returned content is HTML, but it can return more than just the preceding images and PDF files. The key to returning non-HTML content is the HttpResponse class, especially the mimetype parameter. By setting this parameter to a different value, 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 as an image, specify the mimetype of the image in HttpResponse, and use the image content as another parameter response to the browser, 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 to note is that the HttpResponse object implements the Python 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 response
Notes:
1. In HttpResponse, The mimetype is specified as 'text/csv' to inform the browser that the returned document is a csv file.
2. HttpResponse sets another parameter Content-Disposition. attachment tells the browser to save the returned document rather than display its Content. filename indicates the name of the returned document. You can change the name to any one.
3. Because the csv writer method expects an object of the file type as a parameter, and the HttpResponse instance can be used as a file, HttpResponse can be used as a parameter directly in the writer method of the csv module.
4. The writer. writerow method writes a row of content to the file.

The above method is to return a common mode of non-HTML content, that is, to create an HttpResponse for a specific MIME Type and pass it to a file as a parameter to generate a document in a specific format, then return the response.

Generate PDF content

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 response
The process is basically the same as above. Notes:
1. The application/pdf MIME type is used here to inform the browser that the returned pdf file is not HTML, otherwise the browser will treat it as common HTML content.
2. the canvas. Canvas method expects a file-like object as a parameter and passes HttpResponse to the method.
3. Use the Canvas instance method to draw a PDF document and call the showPage () and save () methods (otherwise, a damaged pdf document will be generated ).
4. The HttpResponse instance is returned.

Generate more complex PDF documents. Here the cStringIO library is used to temporarily store PDF files

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 response
Other 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, and XLS files.

Finally, let's look at an example of returning the 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 response
The process is the same as above and is not commented out.

In addition, you must note that the request must be submitted through a form to correctly return the content in a specific format, if a request is initiated using ajax, the returned content is treated as a text string and cannot be interpreted as a specific content by the browser.
For example:
$. Ajax ({url: "{% url 'mycitsm. views. viewXls '%} ", data: postData, type:" POST ", success: function (result) {},}); // No, the following form must be used for submission: var form =$ ("# xlsForm"); form. attr ({action: "{% url 'mycitsm. views. returnXls '%} ", method:" POST "}); form. submit ();
It is necessary to record a problem encountered during development and serialize the form content to a string.
Sometimes all content in the form needs to be serialized into a string consisting of key-value pairs as a whole for URL parameter transmission, and special characters in the value need to be encoded. For example, the following form is provided:

<Form> <div> <input type = "text" name = "a" value = "1" id = "a"/> </div> <input type = "text" value = "2" id = "B"/> </div> <input type = "hidden" name = "c" value = "3" id = "c"/> </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> <input type = "checkbox" name = "f" value = "8" id = "f"/> </div> <input type = "submit" name = "g" value = "Submit" id = "g" /> </div> </form> $ ('form '). submit (function () {alert ($ (this ). serialize (); return false ;}); # output a = 1 & c = 3 & d = 4 & e = 5
Why are the input values of the second text type, the input values of the checkbox type, and the input values of the submit type not serialized? This is because to include the value of a form element in a sequence string, the element must use the name attribute. The second text type input has no name attribute. One of the input values of the checkbox type is not checked, so ....... Serialize () Only serializes the "successful control" into a string. If the button is not used to submit the form, the value of the submit button is not serialized, so the input of the submit type 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 <input> and <textarea>.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.