How Django implements the simultaneous submission of picture text

Source: Internet
Author: User
Tags eval extend json new set

This article is an example of how Django implements the simultaneous submission of picture text. Share to everyone for your reference. The specific analysis is as follows:

jquery has solved a lot of problems for our website development, which has greatly improved our website user experience. To give a simple example, we use AJAX technology to implement the form of asynchronous submission, so that users in the experience of a great change, users in the submission of data can also do some other things.

However, today in the development of a special headache problem, the beginning did not know, thought can be achieved, tangled up for nearly 4 hours, but the result is very disappointing.

The problem is this: to improve the user experience, I decided to use Ajax asynchronous submission, so I used jquery $.post to asynchronously submit the form data, text information can be easily submitted, but how can not submit picture data. What do we do?

Check a lot of information on the Internet, later found that jquery does not support image upload (attachment upload), but there are related plug-ins, so I began to slowly pondering, began to use another special upload file plug-in jquery.ajaxfileupload.js, toss for a long time, can always upload pictures. But new problems have been created.

by Ajaxfileupload to upload a picture asynchronously, you cannot submit text data. It's embarrassing.

Search on the Internet a lot of information, toss for a long time, no Django development of the relevant information, how to do?

Then I found a solution to share with you:

Ideas:

Since the use of the Jquery.ajaxfileupload.js plug-in can not pass the custom parameters, swollen do? Rewrite the plugin yourself. Coincidentally, there are other people have changed the ready-made code, apart, first take to try. The following is the process of my experiment.

1. Front page (partial code):

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The

2. After the change of the jquery.ajaxfileupload.js:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 5, 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 11 9 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148-149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179-18 0 181 182 183 184 185 Jquery.extend ({createuploadiframe:function (id, URI) {//create frame var Frameid = ' juploadframe ' + id; if window. ActiveXObject) {var io = document.createelement (' <iframe id= ' + Frameid + ' "name=" ' + Frameid + ' "/> '); if (typeof uri== ' Boolean ') {io.src = ' javascript:false ';} else if (typeof uri== ' string ') {io.src = URI;}} else {var io = document.createelement (' iframe '); io.id = Frameid; io.name = Frameid;} io.style.position = ' absolute '; Io.style.top = ' -1000px '; Io.style.left = ' -1000px '; Document.body.appendChild (IO); Return IO}, createuploadform:function (ID, Fileelementid, data) {//create form var formid = ' juploadform ' + ID; var file id = ' Juploadfile ' + ID; var form = $ (' <form action= "" method= "POST" name= "' + Formid + '" id= "' + Formid + '" enctype= "Multipart/form-data" > </form> '); var oldelement = $ (' # ' + Fileelementid); var newelement = $ (oldelement). Clone (); $ (oldelement). attr (' id ', fileid); $ (oldelement). before (newelement); $ (oldelement). AppendtO (form); Add support for text parameters if (data) {for (var i in data) {$ (' <input type= "hidden" name= "' + i + '" value= "' + data[i] + '"/> '). Appendto (form); }//set attributes $ (form). CSS (' position ', ' absolute '); $ (form). CSS (' top ', ' -1200px '); $ (form). CSS (' left ', ' -1200px '); $ (form). Appendto (' body '); return form; }, Ajaxfileupload:function (s) {//TODO introduce global settings, allowing the client to modify them for all requests, n OT only Timeout s = jquery.extend ({}, jquery.ajaxsettings, s); var id = new Date (). GetTime () var form = Jquery.createuploadform (ID, S.fileelementid, s.data); var io = jquery.createuploadiframe (ID, S.secureuri); var Frameid = ' juploadframe ' + ID; var formid = ' juploadform ' + ID; Watch for a new set of requests if (S.global &&! jquery.active++) {JQuery.event.trigger ("Ajaxstart");} V Ar requestdone = false; Create the Request object var xml = {} if (S.global) JQuery.event.trigger ("Ajaxsend", [XML, S]); Wait for a response to come back Var UploAdcallback = function (istimeout) {var io = document.getElementById (Frameid); try {if (Io.contentwindow) {Xml.responsetex t = io.contentwindow.document.body?io.contentwindow.document.body.innerhtml:null; Xml.responsexml = io.contentwindow.document.xmldocument?io.contentwindow.document.xmldocument: Io.contentWindow.document; }else if (io.contentdocument) {xml.responsetext = Io.contentDocument.document.body? Io.contentDocument.document.body.innerHTML:null; Xml.responsexml = io.contentdocument.document.xmldocument?io.contentdocument.document.xmldocument: Io.contentDocument.document; }}catch (e) {Jquery.handleerror (s, XML, NULL, E);} if (XML | | | istimeout = = "Timeout") {Requestdone = true; var status; try {status = Istimeout!= "Timeout"? "Success": "Error"; Make sure this request was successful or notmodified if (status!= "error") {//Process the data (runs the XML t Hrough Httpdata regardless of callback) var data = Jquery.uploadhttpdata (XML, S.datatype); If a local calLback is specified, fire it and pass it the data if (s.success) s.success (data, status); Fire the global callback if (S.global) JQuery.event.trigger ("Ajaxsuccess", [XML, S]); else Jquery.handleerror (S, XML, status); catch (e) {status = ' error '; Jquery.handleerror (S, XML, status, E);}//The request was completed if (S.global) jQuery . Event.trigger ("Ajaxcomplete", [XML, S]); Handle the Global AJAX counter if (S.global &&!--jquery.active) JQuery.event.trigger ("Ajaxstop"); Process result if (s.complete) s.complete (XML, status); JQuery (IO). Unbind () settimeout (function () {try {$ (IO). Remove (); $ (form). Remove (); catch (e) {Jquery.handleerror (S, XM L, NULL, E); }}, XML = null}//Timeout checker if (S.timeout > 0) {settimeout (function () {//Check to = if the reques T is still happening if (!requestdone) uploadcallback ("timeout"); }, S.timeout); try {//var IO = $ (' # ' + Frameid); var form = $ (' # ' + formid); $ (form). attr (' action ',S.url); $ (form). attr (' method ', ' POST '); $ (form). attr (' target ', Frameid); if (form.encoding) {form.encoding = ' multipart/form-data ';} else {form.enctype = ' multipart/form-data ';} $ (form). Submit (); catch (E) {Jquery.handleerror (s, XML, NULL, E);} if (window.attachevent) {document.getElementById (Frameid). Attachevent (' onload ', uploadcallback); } else{document.getElementById (Frameid). AddEventListener (' Load ', Uploadcallback, false);} return {abort:function () { }}; }, Uploadhttpdata:function (r, type) {var data =!type; data = Type = = "xml" | | data r.responsexml:r.responsetext; If the type is ' script ', eval it in global context if (type = = "Script") jquery.globaleval (data); Get the JavaScript object, if JSON is used. if (type = = "json") eval ("data =" + data); Evaluate scripts within HTML if (type = = "html") jQuery ("<div>"). HTML (data). Evalscripts (); Alert ($ (' param ', data). each (function () {Alert ($ (this). attr (' value ')); return data; } })

3. Calling methods

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22-23 Save Attachment Information Function Saveannexinfo () {var prove_name = $ ("#id_prove_name"). Val ()//Get value from interface var Prove_type = $ ("#id_prove_typ E "). Val (); var Prove_desc = $ ("#id_prove_desc"). Val (); $.ajaxfileupload ({URL: "/test/annex_info/",//Request URL address Secureuri:false, Fileelementid: ' Id_prove_url ', DataType: ' JSON ', data: {//Added text parameter ' prove_name ':p rove_name, "Prove_type":p rove_type, "Prove_desc":p Rove_desc}, Success:function (data) {asyncbox.tips (' successful operation! ', ' success '); }, Error:function () {asyncbox.tips ("failed to upload), please check that the file meets the format requirements." "); } }); }

4. Python Background Processing (code fragment)

?

1 2 3 4 5 6 7 8 9 If Annex_form.is_valid (): Annex_info = Annex_form.save (commit=false) #获取上传 Annex_url = Request. Files.get (' Prove_url ', ') #取附件 annex_info.entry = Entry_info Annex_info.prove_url = Annex_url annex_info.save () return HttpResponse (1) #操作成功 return HttpResponse (0) #操作失败

I hope this article will help you with your Python programming.

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.