def orderitem(request): current_user = request.user shopcart = ShopCart.objects.filter(user_id=current_user.id) schopcart = ShopCart.objects.filter(user_id=current_user.id) form = OrderForm(request.POST or None) form2 = OrderForm2(request.POST or None) total = 0 for rs in shopcart: total += rs.item.fiyat * rs.quantity if request.method == 'POST': if form.is_valid() and form2.is_valid(): # Send Credit card to bank, If the bank responds ok, continue, if not, show the error # .............. data = Order() data.first_name = form.cleaned_data[ 'first_name'] # get product quantity from form data.last_name = form.cleaned_data['last_name'] data.email = form.cleaned_data['email'] data.address = form2.cleaned_data['address'] data.city = form2.cleaned_data['city'] data.phone = form2.cleaned_data['phone'] data.user_id = current_user.id data.total = total data.ip = request.META.get('REMOTE_ADDR') ordercode = random.randint(100000000, 999999999) # ordercode= get_random_string(9).upper() # random cod data.code = ordercode data.save() for rs in shopcart: detail = OrderItem() detail.order_id = data.id # Order Id detail.item_id = rs.item_id detail.user_id = current_user.id detail.quantity = rs.quantity detail.beden = rs.beden detail.fiyat = rs.item.fiyat detail.save() return redirect(reverse('payment')) else: messages.warning(request, form.errors) return HttpResponseRedirect("/order/orderproduct") form = OrderForm() context = { 'shopcart': shopcart, 'total': total, 'form': form, 'form2': form2, 'schopcart': schopcart, } return render(request, 'order/order_form.html', context)
def create_order_from_express_paypal(nvp_dict): """ Create order in DB with ordered items """ #create order #create items #return order object order = Order() order.email = nvp_dict.get('email') order.b_first_name = nvp_dict.get('firstname') order.b_last_name = nvp_dict.get('lastname') order.b_address_countryname = nvp_dict.get('shiptocountryname') order.b_address_countrycode = nvp_dict.get('shiptocountrycode') order.b_address_zip = nvp_dict.get('shiptozip') order.b_address_state = nvp_dict.get('shiptostate') order.b_address_city = nvp_dict.get('shiptocity') order.b_address_street = nvp_dict.get('shiptostreet') \ + nvp_dict.get('shiptostreet2', "") order.shipping_address_flag = False order.status = order.NEW_ORDER order.paypal_transaction_id = nvp_dict.get('transactionid') order.save() item_ids = [(key, value) for key, value in nvp_dict.iteritems() if key.startswith("l_paymentrequest_0_number")] print item_ids for index, i in enumerate(item_ids): product = Prize.objects.get(pk=i[1]) order_item = OrderItem() order_item.order_id = order.id order_item.product = product order_item.number = product.number order_item.amount = nvp_dict.get('l_paymentrequest_0_amt' + str(index)) order_item.quantity = nvp_dict.get('l_paymentrequest_0_qty' + str(index)) order_item.save() return order
def save_order_items(nvp_dict, order): item_ids = [(key, value) for key, value in nvp_dict.iteritems() if key.startswith("l_paymentrequest_0_number")] print item_ids for index, i in enumerate(item_ids): product = Prize.objects.get(pk=i[1]) order_item = OrderItem() order_item.order_id = order.id order_item.product = product order_item.number = product.number order_item.name = product.name order_item.amount = nvp_dict.get('l_paymentrequest_0_amt' + str(index)) order_item.quantity = nvp_dict.get('l_paymentrequest_0_qty' + str(index)) order_item.size, order_item.color \ = get_size_and_color_from_paypal(nvp_dict.get('l_paymentrequest_0_desc' + str(index))) print nvp_dict.get('l_paymentrequest_0_desc' + str(index)) order_item.save()
def order_add(request, template_name="/"): order = Order() order.date = datetime.datetime.now().strftime("%m/%d/%Y") order.last_updated = datetime.datetime.now().strftime("%m/%d/%Y") order.user = request.user order.ip_address = request.META['REMOTE_ADDR'] print(request.META['REMOTE_ADDR']) print('-----------------------------') print(request) order.transaction_id = 1 order.save() cart_item_list = cart.get_cart_items(request) for item in cart_item_list: order_item = OrderItem() order_item.product = item.product order_item.quantity = item.quantity order_item.price = item.price() order_item.order = order order_item.save() cart.clean(request) url = urlresolvers.reverse('my_account') return HttpResponseRedirect(url)
def create_order_from_direct_paypal(nvp_dict): """ Create order in DB with ordered items """ #create order #create items #return order object """ <QueryDict: {u'l_paymentrequest_0_number0': [4], u's_countrycode': [u'AX'], u'b_state': [u'sdf'], u'card_first_name': [u'sdf'], u's_last_name': [u'sdf'], u's_street': [u'sdf'], u'acct': [u'4239530610456015'], u'l_paymentrequest_0_amt0': [32], u'l_paymentrequest_0_name0': [u'Raw Edge Design Letters Print Black Polyester VEST'], u's_city': [u'sdf'], u's_state': [u'sdf'], u'version': [u'116.0'], u's_countryname': [u'Aland Islands'], u'build': [u'16770825'], u'cvv2': [u'123'], u'b_street': [u'dd'], u'email': [u'*****@*****.**'], u'l_paymentrequest_0_qty0': [2], u'b_countrycode': [u'AU'], u'b_countryname': [u'Afghanistan'], u'timestamp': [u'2015-06-14T10:22:07Z'], u'currencycode': [u'USD'], u'card_last_name': [u'sdf'], u's_zip': [u'dsf'], u'paymentrequest_0_amt': [64.0], u'phone': [u'sdf'], u'b_country': [u'1'], u'cardyear': [u'2020'], u'transactionid': [u'06M899763J781091D'], u'amt': [u'64.00'], u's_first_name': [u'sdf'], u'cvv2match': [u'M'], u'cardmonth': [u'05'], u'ack': [u'Success'], u'b_city': [u'sdf'], u'creditcardtype': [u'visa'], u'b_last_name': [u'dddddd'], u'b_zip': [u'sdf'], u'avscode': [u'X'], u'b_first_name': [u'sads'], u'correlationid': [u'dba9b733e476']}> """ order = Order() order.email = nvp_dict.get('email') order.phone = nvp_dict.get('phone', "") order.b_first_name = nvp_dict.get('b_first_name') order.b_last_name = nvp_dict.get('b_last_name') order.b_address_countryname = nvp_dict.get('b_countryname') order.b_address_countrycode = nvp_dict.get('b_countrycode') order.b_address_zip = nvp_dict.get('b_zip') order.b_address_state = nvp_dict.get('b_state') order.b_address_city = nvp_dict.get('b_city') order.b_address_street = nvp_dict.get('b_street') order.s_first_name = nvp_dict.get('s_first_name', "") order.s_last_name = nvp_dict.get('s_last_name', "") order.s_address_countryname = nvp_dict.get('s_countryname', "") order.s_address_countrycode = nvp_dict.get('s_countrycode', "") order.s_address_zip = nvp_dict.get('s_zip', "") order.s_address_state = nvp_dict.get('s_state', "") order.s_address_city = nvp_dict.get('s_city', "") order.s_address_street = nvp_dict.get('s_street', "") order.status = order.NEW_ORDER order.paypal_transaction_id = nvp_dict.get('transactionid') order.save() item_ids = [(key, value) for key, value in nvp_dict.iteritems() if key.startswith("l_paymentrequest_0_number")] #print item_ids for index, i in enumerate(item_ids): product = Prize.objects.get(pk=i[1]) order_item = OrderItem() order_item.order_id = order.id order_item.product = product order_item.number = product.number order_item.amount = nvp_dict.get('l_paymentrequest_0_amt' + str(index)) order_item.quantity = nvp_dict.get('l_paymentrequest_0_qty' + str(index)) order_item.save() return order
def edit_model(request,model,id,template_name=""): page=request.GET.get('page') if request.method == 'POST': print(request.POST) print('edit') if model == 'category': category = get_object_or_404(Category, id=id) postdata = request.POST.copy() category.name = postdata.get('name') category.slug = slug(category.name) category.updated_at = datetime.datetime.now().strftime("%m/%d/%Y") category.description = postdata.get('description') is_active = postdata.get('is_active') if is_active == "True": category.is_active = True else: category.is_active = False category.save() print('edit category') elif model == 'subcategory': subcategory = get_object_or_404(SubCategory, id=id) subcategory.name = request.POST.get('name') subcategory.description = request.POST.get('description') subcategory.slug = slug(subcategory.name) is_active = request.POST.get('is_active') subcategory.updated_at = datetime.datetime.now().strftime("%m/%d/%Y") if is_active=="True": subcategory.is_active = True else: subcategory.is_active = False subcategory.categories.clear() selected_c = json.loads(request.POST.get('selected_categories')) for s_c in selected_c: c = get_object_or_404(Category, slug=s_c) subcategory.categories.add(c) subcategory.save() print('edit subcategory') elif model == 'product': p = get_object_or_404(Product, id=id) postdata = request.POST.copy() p.name = postdata.get('name') product_name = postdata.get('name') p.brand = postdata.get('brand') p.sku = postdata.get('sku') p.price = postdata.get('price') p.old_price = postdata.get('old_price') p.quantity = postdata.get('quantity') p.description = postdata.get('description') user = get_object_or_404(MyUser, username=postdata.get('user')) p.user = user p.slug = slug(p.name) is_active = request.POST.get('is_active') if is_active=="True": p.is_active = True else: p.is_active = False p.updated_at = datetime.datetime.now().strftime("%m/%d/%Y") if request.FILES: print('image_exist') ## delete image ### os.remove(MEDIA_ROOT+'images/products/thumbnails/'+p.image) os.remove(MEDIA_ROOT+'images/products/main/'+p.image) ################### p_main_file=request.FILES['img'] file_extention = os.path.splitext(str(request.FILES['img']))[1] # print(file_extention) # file_name = str(request.FILES['img']).split('.') # file_extention = file_name[len(file_name)-1] image_name = str(user)+'_'+p.name+file_extention p_thumbnail_file=request.FILES['img'] with open(MEDIA_ROOT+'images/products/thumbnails/'+image_name, 'wb+') as destination: if p_thumbnail_file.multiple_chunks(): for chunk in p_thumbnail_file.chunks(): destination.write(chunk) else: destination.write(p_thumbnail_file.read()) with open(MEDIA_ROOT+'images/products/thumbnails/'+image_name, 'rb+') as destination: image_file = destination.read() with open(MEDIA_ROOT+'images/products/main/'+image_name, 'wb+') as destination: destination.write(image_file) p.image=image_name else: print('image_empty') # p.save() p.subcategories.clear() selected_subc = json.loads(request.POST.get('selected_subcategories')) for p_subc in selected_subc: subc = get_object_or_404(SubCategory, slug=p_subc) p.subcategories.add(subc) p.save() print('edit product') elif model == 'myuser': user = get_object_or_404(MyUser, id=id) postdata = request.POST.copy() # print(postdata) user.username = postdata.get('name') user.first_name = postdata.get('first_name') user.last_name = postdata.get('last_name') user.date_of_birth = postdata.get('date_of_birth') user.address = postdata.get('address') user.telephone = postdata.get('telephone') # user.password = make_password(postdata.get('password')) is_active = postdata.get('is_active') if is_active=="True": user.is_active = True else: user.is_active = False is_staff = postdata.get('is_staff') if is_staff=="True": user.is_staff = True else: user.is_staff = False is_superuser = postdata.get('is_superuser') if is_superuser=="True": user.is_superuser = True else: user.is_superuser = False user.user_permissions.clear() selected_permissions= json.loads(request.POST.get('selected_permissions')) for s_p in selected_permissions: perm = get_object_or_404(Permission, codename=s_p) user.user_permissions.add(perm) user.save() print('edit myuser') elif model == 'order': order = get_object_or_404(Order, id=id) postdata = request.POST.copy() myuser = get_object_or_404(MyUser, username=postdata.get('user')) order.address = myuser.address order.phone = myuser.telephone order_status = get_object_or_404(OrderStatus, id= postdata.get('status')) order.status = order_status order.ip_address = postdata.get('ip_address') order.user = myuser order.transaction_id = postdata.get('transaction_id') order.last_updated = datetime.datetime.now().strftime("%m/%d/%Y") order.save() print(order.id); item = OrderItem.objects.filter(order=order) for i in item: i.delete() cart_items = cart.get_cart_items(request) for c in cart_items: orderitem = OrderItem() orderitem.product = c.product orderitem.price = c.price() orderitem.quantity = c.quantity orderitem.order = order orderitem.save() print('edit order') elif model == 'orderitem': orderitem = get_object_or_404(OrderItem, id=id) postdata = request.POST.copy() product = get_object_or_404(Product, slug=postdata.get('product')) orderitem.product = product orderitem.price = product.price orderitem.quantity = postdata.get('quantity') order = get_object_or_404(Order, id=postdata.get('order')) orderitem.order = order orderitem.save() print('edit orderitem') url = urlresolvers.reverse('model',kwargs = {'model':model})+'?page='+page return HttpResponseRedirect(url) # return show_model(request,model,page,'') else: app_list = permission_app(request) # print('_________________edit_permission_________________') if check_permission(request,'edit',model): if model == 'category': category = get_object_or_404(Category, id=id) elif model == 'subcategory': category = Category.objects.all() subcategory = get_object_or_404(SubCategory, id=id) print('subcategory') categories = [] for cate in subcategory.categories.all(): categories.append(slug(cate.name)) categories = json.dumps(categories) # print(categories) elif model == 'product': user_list = MyUser.objects.all() subcategory = SubCategory.objects.all() product = get_object_or_404(Product, id=id) subcategories = [] for subc in product.subcategories.all(): subcategories.append(slug(subc.name)) subcategories = json.dumps(subcategories) print('product') # print(subcategories) elif model == 'myuser': print('myuser') myuser = get_object_or_404(MyUser, id=id) user_permissions = myuser.get_all_permissions() all_permissions = Permission.objects.all() # for a in all_permissions: # print (a.codename) selected_permissions = [] for s_p in user_permissions: s_p_list = s_p.split('.') selected_permissions.append(s_p_list[1]) selected_permissions = json.dumps(selected_permissions) # print(selected_permissions) # print('--------permission------------') # print(all_permissions) elif model == 'order': user_list = MyUser.objects.all() order = get_object_or_404(Order, id=id) product = Product.objects.all() order_status = OrderStatus.objects.all() orderitem = OrderItem.objects.filter(order = order) print(orderitem) cart.clean(request) for o_i in orderitem: cart.add_orderitem_to_cart(o_i,request) cart_items = cart.get_cart_items(request) cart_items_list = [] for c in cart_items: # print(c) item = {} item.setdefault('image',c.image()) item.setdefault('name',c.name()) item.setdefault('quantity',c.quantity) price = str(c.price()) item.setdefault('price',price) total = str(c.total()) item.setdefault('total',total) item.setdefault('id',c.id) # print(item) cart_items_list.append(item) # print(order.status) # print(order.ORDER_STATUSES[0][1]) print('order') elif model == 'orderitem': product = Product.objects.all() order_list = Order.objects.all() orderitem = get_object_or_404(OrderItem, id=id) cart.clean(request) for o in orderitem: cart.add_orderitem_to_cart(o) cart_items = CartItem print('orderitem') # subcategories = SubCategory.objects.all() template_name = 'myadmin/edit/'+model+'.html' return render_to_response(template_name, locals(),context_instance=RequestContext(request)) else: template_name = 'myadmin/err.html' return render_to_response(template_name, locals(),context_instance=RequestContext(request))
def add_model(request,model,template_name=""): # show_model(request,model,template_name) # print(); result = ""; if request.method == 'POST': print('add') if request.POST.get('mode')=='add_cart_item': cart.add_to_cart(request) cart_items_list = [] cart_items = cart.get_cart_items(request) # serializers.serialize("json", ) cart_item_count = cart.cart_distinct_item_count(request) # result = {'cart_items' : cart_items ,'cart_item_count' : cart_item_count} # print(cart_item_count) for c in cart_items: # print(c) item = {} item.setdefault('image',c.image()) item.setdefault('name',c.name()) item.setdefault('quantity',c.quantity) price = str(c.price()) item.setdefault('unit_price',price) total = str(c.total()) item.setdefault('total_price',total) item.setdefault('id',c.id) # print(item) cart_items_list.append(item) # print(cart_items_list) # cart_items = serializers.serialize("json", cart_items_list) # print(cart_items) result = {'cart_items' : cart_items_list ,'cart_item_count' : cart_item_count} # print(json.dumps(result)) print('++++++++++++++++++++++++++++++') return HttpResponse(json.dumps(result),content_type='application/javascript; charset=utf-8') else: if model == 'people': name = request.POST.get('name') islug = slug(name) category = Category() category.name = name category.description = request.POST.get('description') is_active = request.POST.get('is_active') if is_active=="on": category.is_active = True else: category.is_active = False category.slug = islug category.updated_at = datetime.datetime.now().strftime("%m/%d/%Y") category.created_at = datetime.datetime.now().strftime("%m/%d/%Y") category.save() result = "saved" print('add people') elif model == 'subcategory': subcategory = SubCategory() subcategory.name = request.POST.get('name') subcategory.description = request.POST.get('description') subcategory.slug = slug(subcategory.name) is_active = request.POST.get('is_active') subcategory.updated_at = datetime.datetime.now().strftime("%m/%d/%Y") subcategory.created_at = datetime.datetime.now().strftime("%m/%d/%Y") if is_active=="on": subcategory.is_active = True else: subcategory.is_active = False subcategory.save() selected_c = json.loads(request.POST.get('selected_categories')) for s_c in selected_c: c = get_object_or_404(Category, slug=s_c) subcategory.categories.add(c) subcategory.save() print('add subcategory') elif model == 'product': p = Product() postdata = request.POST.copy() p.name = postdata.get('name','a') product_name = postdata.get('name','a') p.brand = postdata.get('brand') p.sku = postdata.get('sku') p.price = postdata.get('price') p.old_price = postdata.get('old_price') p.quantity = postdata.get('quantity') p.description = postdata.get('description') # print(postdata.get('user')) user = get_object_or_404(MyUser, username=postdata.get('user')) p.user = user p.slug = slug(p.name) is_active = request.POST.get('is_active') if is_active=="on": p.is_active = True else: p.is_active = False p.updated_at = datetime.datetime.now().strftime("%m/%d/%Y") p.created_at = datetime.datetime.now().strftime("%m/%d/%Y") if request.FILES: print('image_exist') p_main_file=request.FILES['img'] file_extention = os.path.splitext(str(request.FILES['img']))[1] # print(file_extention) # file_name = str(request.FILES['img']).split('.') # file_extention = file_name[len(file_name)-1] image_name = str(user)+'_'+p.name+file_extention p_thumbnail_file=request.FILES['img'] with open(MEDIA_ROOT+'images/products/thumbnails/'+image_name, 'wb+') as destination: if p_thumbnail_file.multiple_chunks(): for chunk in p_thumbnail_file.chunks(): destination.write(chunk) else: destination.write(p_thumbnail_file.read()) with open(MEDIA_ROOT+'images/products/thumbnails/'+image_name, 'rb+') as destination: image_file = destination.read() with open(MEDIA_ROOT+'images/products/main/'+image_name, 'wb+') as destination: destination.write(image_file) p.image=image_name else: print('image_empty') p.image='default' p.save() selected_subc = json.loads(request.POST.get('selected_subcategories')) for p_subc in selected_subc: subc = get_object_or_404(SubCategory, slug=p_subc) p.subcategories.add(subc) p.save() print('add product') elif model == 'myuser': user = MyUser() postdata = request.POST.copy() user.username = postdata.get('name') user.first_name = postdata.get('first_name') user.last_name = postdata.get('last_name') ##########change date format###########YYYY-MM-DD # date_of_birth = postdata.get('date_of_birth') # date_list = date_of_birth.split('/') # join_str = '-' # user.date_of_birth = join_str.join(date_list) user.date_of_birth = postdata.get('date_of_birth') ######################################## user.address = postdata.get('address','a') user.telephone = postdata.get('telephone') user.password = make_password(postdata.get('password')) user.is_active = True user.is_staff = True user.save() print('add myuser') elif model == 'order': order = Order() postdata = request.POST.copy() myuser = get_object_or_404(MyUser, username=postdata.get('user')) print(postdata) order.address = myuser.address order.phone = myuser.telephone order_status = get_object_or_404(OrderStatus, id=postdata.get('status')) print(order_status.name) order.status = order_status order.ip_address = postdata.get('ip_address') # user = get_object_or_404(MyUser, username=postdata.get('user')) order.user = myuser order.transaction_id = postdata.get('transaction_id') order.last_updated = datetime.datetime.now().strftime("%m/%d/%Y") order.save() print(order.id); cart_items = cart.get_cart_items(request) for c in cart_items: orderitem = OrderItem() orderitem.product = c.product orderitem.price = c.price() orderitem.quantity = c.quantity orderitem.order = order orderitem.save() print('add order') elif model == 'orderitem': orderitem = OrderItem() postdata = request.POST.copy() product = get_object_or_404(Product, slug=postdata.get('product')) orderitem.product = product orderitem.price = product.price orderitem.quantity = postdata.get('quantity') order = get_object_or_404(Order, id=postdata.get('order')) orderitem.order = order orderitem.save() print('add orderitem') # return show_model(request,model,'') url = urlresolvers.reverse('model',kwargs = {'model':model}) return HttpResponseRedirect(url) else: app_list = permission_app(request) # print('_________________addpermission_________________') if check_permission(request,'add',model): if model == 'people': print('category') elif model == 'subcategory': category = Category.objects.all() print('subcategory') elif model == 'product': user_list = MyUser.objects.all() subcategory = SubCategory.objects.all() print('product') print(subcategory) elif model == 'myuser': print('myuser') elif model == 'order': cart.clean(request) user_list = MyUser.objects.all() product = Product.objects.all() order_status = OrderStatus.objects.all() # print(request.GET) # print('-------------------------------') # cart.add_to_cart(request) # cart_items = serializers.serialize("json", cart.get_cart_items(request)) # cart_item_count = cart.cart_distinct_item_count(request) # result = {'cart_items' : cart_items ,'cart_item_count' : cart_item_count} # print(result) # print('++++++++++++++++++++++++++++++=') # return HttpResponse(json.dumps(result),content_type='application/javascript; charset=utf-8') print('order') elif model == 'orderitem': product = Product.objects.all() order_list = Order.objects.all() print('orderitem') # subcategories = SubCategory.objects.all() template_name = 'myadmin/add/'+model+'.html' return render_to_response(template_name, locals(),context_instance=RequestContext(request)) else: template_name = 'myadmin/err.html' return render_to_response(template_name, locals(),context_instance=RequestContext(request))
def success(request): from order.utils import generate_order_pdf from django.template.loader import render_to_string from django.core import mail from django.core.mail import EmailMultiAlternatives, EmailMessage from django.contrib.auth.models import Group try: order = request.session['order'] except KeyError: raise Http404 if order.user != request.user: raise Http404 cart = get_cart(request) cart = archive_cart(cart) order.cart = cart.id order.save() del request.session['cart'] voucher = request.session['voucher'] if 'voucher' in request.session else None items = ArchivedCartItem.objects.filter(archived_cart=cart) for item in items: order_item = OrderItem() order_item.order = order order_item.product = item.product order_item.quantity = item.quantity order_item.discount_total = item.discount_total order_item.gross_total = item.gross_total order_item.net_total = item.net_total order_item.save() #Update sold figure item.product.sold += item.quantity item.product.save() order.status = 1 order.save() pdf = generate_order_pdf(request.get_host(), order, voucher) subject = _('EMPOR Order Confirmation') html_content = render_to_string('order/email.html', { 'order': order, 'items': items, 'voucher': voucher, 'STATIC_URL': settings.STATIC_URL, 'host': request.get_host() }) text_content = render_to_string('order/email.txt', { 'order': order, 'voucher': voucher, 'items': items, 'host': request.get_host() }) connection = mail.get_connection() connection.open() message = EmailMultiAlternatives(subject, text_content, settings.DEFAULT_FROM_EMAIL, [order.user.email]) message.attach_alternative(html_content, 'text/html') filename = order.order_id message.attach(filename.encode('utf-8'), pdf, 'application/pdf') group = Group.objects.get(name='Service').user_set.only('email') subject = 'EMPOR - 新訂單 %s' % order.order_id group_email = [ user.email for user in group ] notification = EmailMessage(subject, html_content, settings.DEFAULT_FROM_EMAIL, group_email) notification.content_subtype = 'html' connection.send_messages([message, notification]) connection.close() if 'voucher' in request.session: del request.session['voucher'] return redirect('order-thankyou')
def handle(self, *args, **options): file_path = args[0] if not os.path.isfile(file_path): self.stdout.write('File %s not exists' % args[0]) json_file = open(file_path) orders = json.loads(json_file.read()) for order in orders: print(order['id']) try: user = User.objects.get(username=str(order['user_id'])) except User.DoesNotExist: continue try: new_order = Order.objects.get(pk=order['id']) except Order.DoesNotExist: print('Does.NotExist') new_order = Order(user=user, total_price=0) new_order.city = order['city'] print(order['address']) new_order.address_street = order['address'][:63] new_order.total_price = float(order['total']) #new_order.payment_method = order['payment_method'] new_order.phone = order['phone'][:31] new_order.address_zipcode = order['zip_code'] new_order.add_time = order['timestamp'] new_order.user = user client_name = client_name_len = None if order['fullname']: client_name = order['fullname'].split(' ') else: client_name = None client_name_len = len(client_name) if client_name else 0 client_first_name = client_second_name = client_last_name = None if client_name_len > 0: client_last_name = client_name[0] if client_name_len > 1: client_first_name = client_name[1] if client_name_len > 2: client_second_name = client_name[2] new_order.client_name = client_first_name or "" new_order.client_second_name = client_second_name new_order.client_last_name = client_last_name new_order.save() items = order['items'] for item in items: new_item = OrderItem() new_item.order = new_order new_item.scale = item['scale'] new_item.name = item['title'] #new_item. = item['url'] new_item.price = float(item['price']) new_item.article = item['article'] new_item.quantity = item['quantity'] new_item.manufacturer = item['manufacturer'] try: new_item.item = Item.objects.get(article=new_item.article) except Item.DoesNotExist: continue new_item.save() # order['shipping_method'] # order['comments'] # discount = order['discount'] # order['state'] # order['total_without_discount'] # order['shipping_price'] # # order['fullname'] #