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 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 form_valid(self, form): self.object = form.save() # Fetch all products basket = self.request.session.get('basket', []) products_in_basket = [item.get('product') for item in basket] products = Product.objects.filter(pk__in=products_in_basket, active=True, shop__active=True).order_by('shop') products_dict = {product.pk: product for product in products} # Total cost & valid items list per shop shop_items_and_cost = dict.fromkeys( {product.shop for product in products}) for key in shop_items_and_cost: shop_items_and_cost[key] = { 'total_cost': Decimal(0.00), 'order_items': [], 'item_count': 0 } # Create orderItems for item in basket: product = products_dict[item.get('product')] count = item.get('count') # If product is not found, skip product if product is None: continue # If count is 0 or below, skip item if count < 1: continue order_item = OrderItem() order_item.product = product order_item.order = self.object order_item.count = count # Save the offer/on sale price if any, else use normal price order_item.price = product.offer_price if product.offer_price else product.price order_item.save() shop_items_and_cost[product.shop]['item_count'] += count shop_items_and_cost[product.shop]['total_cost'] += Decimal( order_item.subtotal()) shop_items_and_cost[product.shop]['order_items'].append(order_item) context = { 'order': self.object, 'shop_items_and_cost': shop_items_and_cost } html_message = render_to_string('emails/order_confirmation.html', context) txt_message = render_to_string('emails/order_confirmation.txt', context) subject = gettext('Order confirmation') self.object.status = Order.ORDERED email = EmailMultiAlternatives(subject, txt_message) email.from_email = settings.DEFAULT_FROM_EMAIL email.to = [self.object.email] email.attach_alternative(html_message, "text/html") email.content_subtype = 'html' email.mixed_subtype = 'related' with open('base/static/base/img/fb_logo.png', mode='rb') as f: image = MIMEImage(f.read()) image.add_header('Content-ID', "<Foodbee_logo_long.png>") email.attach(image) email.send() # Clear session self.request.session.flush() return HttpResponseRedirect(self.get_success_url())
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'] #