This article mainly introduces Django's method of submitting Image text at the same time, and analyzes in detail the skills related to simultaneous submission of images and text by Django + jQuery, for more information about how to submit images and texts simultaneously, see the example in this article. Share it with you for your reference. The specific analysis is as follows:
JQuery solves many problems for our website development, greatly improving our website user experience. For example, AJAX technology is used to implement asynchronous form submission, which greatly improves the user experience, you can do other things while submitting data.
However, I encountered a special headache during development today. I didn't know it at the beginning. I thought it could be done. it had been around for nearly four hours, but the result was disappointing.
The problem is: to improve user experience, I decided to use AJAX for asynchronous submission, so I used jQuery's $. post submits form data asynchronously. text information can be easily submitted, but image data cannot be submitted. What should we do?
I checked a lot of information on the internet and found that jQuery does not support Image upload (attachment Upload), but there are related plug-ins, so I began to think about it slowly, start using another plug-in called jquery. ajaxfileupload. js. after a long time, you can always upload images. However, new problems arise.
While uploading images asynchronously through ajaxfileupload, you cannot submit text data. Sorry .......
I checked a lot of information on the Internet, and it took a long time to get rid of Django development-related information. what should I do? Find a solution .......
Then I found the solution and shared it with you:
Ideas:
Since the jquery. ajaxfileupload. js plug-in cannot pass custom parameters, is it swollen? Rewrite the plug-in by yourself. As a coincidence, there is a ready-made code that someone else has modified on the internet. if you don't want to say anything, try it first. The following is my experiment process.
1. front-end page (some code ):
| Certificate name: |
|
|
|
| Document type: |
ID card Degree certificate Other certificates |
|
|
| Certificate description: |
|
|
|
| Attachment address: |
|
|
|
| |
2. the modified jquery. ajaxfileupload. js:
JQuery. extend ({createUploadIframe: function (id, uri) {// create frame var frameId = 'juploadframe '+ id; if (window. activeXObject) {var io = document. createElement (''); 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 fileId = 'juploadfile' + id; var form = $ (''); var oldElement = $ ('#' + fileElementId); var newElement = $ (oldElement ). clone (); $ (oldElement ). attr ('id', fileId); $ (oldElement ). before (newElement); $ (oldElement ). appendTo (form); // added support for if (data) {for (var I in data) {$ (''). AppendTo (form) ;}}// set attributes (form).css ('position', 'absolute '); parameters (form).css ('top','-effectpx '); parameters (form).css ('left ', '-margin PX'); $ (form ). appendTo ('body'); return form;}, ajaxFileUpload: function (s) {// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery. extend ({}, jQuery. ajaxSettings, s); var id = new Date (). getTime () var M = 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");} var 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. responseText = io.content+doc ument. body? Io.contentdomaindoc ument. body. innerHTML: null; xml. responseXML = io.content+doc ument. XMLDocument? Io.contentcontactdoc ument. XMLDocument: io.contentcontactdoc ument;} else if (io. contentDocument) {xml. responseText = io.contentDocument.doc ument. body? Io.contentDocument.doc ument. body. innerHTML: null; xml. responseXML = io.contentDocument.doc ument. XMLDocument? Io.contentDocument.doc ument. XMLDocument: io.contentDocument.doc ument;} catch (e) {jQuery. handleError (s, xml, null, e);} if (xml | isTimeout = "timeout") {requestDone = true; var status; try {status = isTimeout! = "Timeout "? "Success": "error"; // Make sure that the request was successful or notmodified if (status! = "Error") {// process the data (runs the xml through httpData regardless of callback) var data = jQuery. uploadHttpData (xml, s. dataType); // If a local callback was 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, xml, null, e) ;}, 100) xml = null }// Timeout checker if (s. timeout> 0) {setTimeout (function () {// Check to see if the request 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 (""Pai.html (data ). evalScripts (); // alert ($ ('param', data ). each (function () {alert ($ (this ). attr ('value') ;}); return data ;}})
3. call method
// Save the attachment information function saveincluinfo () {var prove_name =_name ("# id_prove_name "). val (); // obtain the value var prove_type = $ ("# id_prove_type") from the interface "). val (); var prove_desc = $ ("# id_prove_desc "). val (); $. ajaxFileUpload ({url: "/test/cmd_info/", // The Request Url secureuri: false, fileElementId: 'id _ prove_url ', Ype: 'json', data: {// added text parameter "prove_name": prove_name, "prove_type": prove_type, "prove_desc": prove_desc}, success : Function (data) {asyncbox. tips ('Operation successful! ', 'Success') ;}, error: function () {asyncbox. tips ("Upload failed. check whether the file meets the format requirements. ");}});}
4. Python background processing (code snippets)
If pai_form.is_valid (): pai_info = pai_form.save (commit = False) # get Upload pai_url = request. FILES. get ('prove _ url', '') # obtain the attachment pai_info.entry = entry_info pai_info.prove_url = pai_url pai_info.save () return HttpResponse (1) # return HttpResponse (0) # operation failed
I hope this article will help you with Python programming.