def format_and_save_contact(user_id, list_data): contact_data_list = [] utils = Utils() for i, d in enumerate(list_data): fields_list = [] contact_data = { 'name': '', 'is_vendor': False, 'is_customer': True, 'contact_type': 'I', 'profile_image': '', 'user_id': user_id, 'company_id': 0, 'parent_id': 0, 'fields': [] } contact_data['profile_image'] = utils.get_profile_image(i) for key in d: value = utils.comma_sep_value(d[key]) if key == 'name': contact_data['name'] = value else: temp_dic = {'id': key, 'value': value} fields_list.append(temp_dic) contact_data['fields'] = fields_list contact_data_list.append(contact_data) save_in_db(contact_data) return True
def contact_import_mapping(request): contact_list = {'success': False, 'file': ''} user_id = request.user.id utils = Utils() if request.method == "POST" and request.is_ajax(): if 'file_name' in request.POST: file_name = request.POST['file_name'] fields = json.loads(request.POST['fields']) if fields.count('0') == len(fields): contact_list = { 'success': False, 'file': '', 'msg': 'You did not selected any fields.' } return HttpResponse(json.dumps(contact_list), content_type="application/json") file_path = 'media/user_csv/' + str(request.user.id) uploaded_file_url = settings.BASE_DIR + '/' + file_path + '/' + file_name try: with open(uploaded_file_url, "r", encoding="latin-1") as csvfile: dialect = csv.Sniffer().sniff(csvfile.read(), delimiters=';,') csvfile.seek(0) reader = csv.reader(csvfile, dialect=dialect) file_rows = [] try: for line_number, row in enumerate(reader): if len(row) > 1: temp_dic = {} for idx, col in enumerate(fields): temp_list = [] if col != '0': if row[idx]: if fields[idx] in temp_dic: temp_list.append( utils.comma_sep_value( temp_dic[fields[idx]])) temp_list.append(row[idx]) temp_dic[ fields[idx]] = temp_list else: temp_dic[ fields[idx]] = row[idx] file_rows.append(temp_dic) if len(file_rows) > 0: format_and_save_contact(user_id, file_rows) contact_list['csv_cols'] = file_rows contact_list['success'] = True os.remove(uploaded_file_url) except csv.Error as e: sys.exit('file %s, line %d: %s' % (uploaded_file_url, reader.line_num, e)) except IOError as e: print("I/O error({0}): {1}".format(e.errno, e.strerror)) return HttpResponse(json.dumps(contact_list), content_type="application/json")