The example of this article for everyone to share the Web page in the use of Ajax to achieve the bulk import data function of the implementation method for your reference, the specific contents are as follows
url.py Code:
Copy Code code as follows:
URL (r ' ^workimport/$ ', ' keywork.views.import_keywork ', name= ' import_keywork ')
view.py Code:
From keywork.models import devdata from django.http import Jsonresponse #django ajax part def import_keywork (request): Fil E_SJDR = Request. post[' file_keywork '] f = open (FILE_SJDR) worklist = [] Next (f) #将文件标记移到下一行 x = y = 0 for line in f:parts = Line.re Place (' ', ') #将字典中的 replace empty parts = Parts.split (', ') #按; Slice the string if DevData.objects.filter (serv_id = parts[0],user_flag=p ARTS[15]). Exists (): x = x + 1 else:y = y + 1 worklist.append (Devdata (serv_id=parts[0), serv_state_name=parts[1 ], acc_nbr=parts[2], user_name=parts[3], acct_code=parts[4], product_id=parts[5], mkt_chnl_name=parts[6], Mkt_chnl_ ID=PARTS[7],MKT_REGION_NAME=PARTS[8], mkt_region_id=parts[9],mkt_grid_name=parts[10], Sale_man=parts[11],sale_ OUTLETS_CD1_NAME=PARTS[12], completed_time=parts[13],remove_data=parts[14], user_flag=parts[15], pro_flag=parts[ ], service_offer_id=parts[17],service_offer_name=parts[18], finish_time=parts[19],staff_name=parts[20], staff_ code=parts[21],org_NAME=PARTS[22],PROD_OFFER_NAME=PARTS[23],DAY_ID=PARTS[24]) F.close () DevData.objects.bulk_create (worklist)
num = {' success ': Str (y), ' fail ': str (x), ' Sum ': str (x+y)} return Jsonresponse (num)
This section of code references the previous article (Django Bulk Import does not duplicate data )
Code in Template:
$ (' #btn_sjdr '). Click (function () {
$.post ("{% url ' import_keywork '%}",
{
csrfmiddlewaretoken: "{csrf_ Token}} ",
file_keywork:$ (" #file_keywork "). Val (),
},
function (data,status) {
$ (" #test1 "). HTML ( status+ "Duplicate data" +data[' fail ']+ "bar, successfully import data" +data[' success ']+ ' ")
}
); <form>
{% csrf_token%}
<label><i class= "icon-file" ></i> Please select the file you want to import </label >
<input id= "file_keywork" type= "file"/> <input "button" type= "id=" BTN_SJDR "
import" value= " btn btn-primary btn-sm "/>
</form>
<div id=" test1 "></div>
</div>
form with Post+ajax, note that in Django submitting a form using the Post method satisfies two conditions:
In the form add {% Csrf_token%}, add Csrfmiddlewaretoken in jquery code: "{{Csrf_token}}", you can!
The above is the entire content of this article, I hope to help you learn.