How to generate non-HTML-formatted content in Django.

Source: Internet
Author: User

Sometimes there may be a need to click on a link or a button in a webpage to return an image, a PDF document, a CSV document, and not HTML. It's easy to do this in Diango. The view in Django is used to receive HTTP request and return to Web response. Typically, the returned content is HTML, but it can return more than just that, but also the above image, pdf file, and so on. The key to returning non-HTML content is the HttpResponse class, especially the MimeType parameter, which, by setting this parameter to a different value, prompts the browser view to return content in a different format. For example, if you want to return the image content, just read one image, then specify the picture's mimetype in HttpResponse and response the picture content as another parameter to the browser, the browser can automatically display the picture content correctly.

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 important thing to note is that the HttpResponse object implements Python's standard "File-like-object" API, which means that httpresponse can be used 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# the 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
A few things to note:
1.HttpResponse mimetype Specifies that the document returned by the browser for ' Text/csv ' is a CSV file.
2.HttpResponse set another parameter content-disposition where attachment tells the browser to save the returned document instead of displaying its contents, and filename Specifies the name of the returned document, which can be arbitrarily specified.
3. Because the writer method of the CSV expects an object of a file type as a parameter, and the HttpResponse instance can be used as a file, you can use HttpResponse as a parameter directly in the writer method of the CSV module.
The 4.writer.writerow method is responsible for writing a line of content to the file.

The above method is a common pattern for returning non-HTML-formatted content, that is, to create a httpresponse of a specific MIME type, passing it to a file as a method of producing 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 (+, "Hello world.")    # Close The PDF object cleanly, and we ' re done.    P.showpage ()    p.save ()    return response
The process is the same as above, some points to note:
1. The Application/pdf MIME type is used here to tell the browser to return a PDF file rather than HTML, otherwise the browser will treat it as normal HTML content.
2.canvas. The canvas method expects a File-like object as a parameter to pass HttpResponse to the method.
3. Use the Canvas instance method to draw the PDF document, calling the ShowPage () method and the Save () method (otherwise creating a corrupted PDF document).
4. Finally return to the HttpResponse instance

Generate more complex PDF documents using the Cstringio library for temporary storage of 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 (+, "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 HttpResponse to return content in a specific format, such as ZIP files, animated images, charts, XLS files, and so on.

And finally looking at an example that returns 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 response
Process above, not comment.

In addition, it is important to note that the request here must be submitted through the form to correctly return the content in a particular format, and the content returned by the request that is initiated by Ajax is treated as a text string and cannot be interpreted as a specific content by the browser.
Like what:
$.ajax ({                URL: "{% url ' mycitsm.views.viewXls '%}",                Data:postdata,                type: "POST",                success:function ( Result) {                },       });//is not possible, but to use the following form submission can be: var form = $ ("#xlsForm"); Form.attr ({action: "{% URL ') Mycitsm.views.returnXls '%} ', method: "POST"        }); Form.submit ();
Speaking of which, it is necessary to document a problem encountered during the development process and to serialize the form content to a string.
Sometimes it is necessary to serialize all the contents of a form into a string made up of key-value pairs for a whole URL parameter pass, and to encode the special characters contained in the value. For example, there are the following forms:

<form > <div><input type= "text" Name= "a" value= "1" id= "a"/></div> <div><input type= "text" Valu E= "2" id= "B"/></div> <div><input type= "hidden" name= "C" value= "3" id= "C"/></div> <DIV&G    T <textarea name= "D" rows= "8" cols= ">4</textarea>" </div> <div><select name= "E" > <op tion 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>$ (' for  M '). Submit (function () {alert (this). Serialize ()); return false;}); #可以输出a =1&c=3&d=4&e=5 
Why is the value of input of the second text type also has the value of the checkbox type input and the input of the submit type is not serialized? This is because if the value of the form element is to be included in the sequence string, the element must use the Name property. The second text type, input, has no Name property. One of the checkbox type input has not been checked so .... Serialize () Serializes the successful control to a string only. If you do not use a button to submit the form, the value of the Submit button is not serialized, so input of the submit type is not serialized.
Of course, in addition to the entire form sequence, you can also serialize the jquery object for the selected individual form elements, such as <input>,<textarea> and so on.



How to generate non-HTML-formatted content in Django.

Related Article

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.