Home > Article > Web Front-end > Django framework uses ajax to implement batch import data function
This article mainly introduces the relevant information about the Django framework using ajax to implement the batch import data function. Friends in need can refer to it
The example of this article shares with you the use of ajax to implement the batch data import function in the web page. The implementation method is for your reference. The specific content is as follows
url.py code:
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部分 def import_keywork(request): file_sjdr = request.POST['file_keywork'] f = open(file_sjdr) WorkList = [] next(f) #将文件标记移到下一行 x = y = 0 for line in f: parts = line.replace('"','') #将字典中的"替换空 parts = parts.split(',') #按;对字符串进行切片 if DevData.objects.filter(serv_id = parts[0],user_flag=parts[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[16], 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)
Code in the template:
$('#btn_sjdr').click(function(){ $.post("{% url 'import_keywork' %}", { csrfmiddlewaretoken:"{{ csrf_token }}", file_keywork:$("#file_keywork").val(), }, function(data,status) { $("#test1").html(status+"重复数据"+data['fail']+"条,成功导入数据"+data['success']+"条"); } ) }); <form> {% csrf_token %} <label><i class="icon-file"></i> 请选择需要被导入的文件</label> <input id="file_keywork" type="file"/> <input type="button" id="btn_sjdr" value="导入" class="btn btn-primary btn-sm"/> </form> <p id="test1"></p> </p>
The form uses post ajax. Note that using the post method to submit the form in Django must meet two conditions:
Add {% csrf_token in the form %}, add csrfmiddlewaretoken: "{{ csrf_token }}" in the jquery code, that's it!
The above is what I compiled for everyone, I hope it will be helpful to everyone in the future.
Related articles:
AJAX request queue implementation
##Summary of several methods of using ajax to submit forms asynchronously
How to solve the problem of arrays in AJAX requests
##
The above is the detailed content of Django framework uses ajax to implement batch import data function. For more information, please follow other related articles on the PHP Chinese website!