class OrderFormTest(testcases.TestCase): def setUp(self) -> None: self.user = MyUser.objects.create_user(username="******", password="******") self.product = Product.objects.create(name="1", description="", amount=10, cost=10) self.correct_form = OrderForm({ "user": self.user, "product": self.product, "amount": 1 }) self.incorrect_form = OrderForm({ "user": self.user, "product": self.product, "amount": 0 }) def test_form_with_valid_amount(self): self.assertTrue(self.correct_form.is_valid()) def test_form_with_invalid_amount(self): self.assertFalse(self.incorrect_form.is_valid()) def test_form_with_invalid_amount_error_message(self): self.assertEquals(self.incorrect_form.errors["amount"][0], "Invalid amount")
def order_detail(request): currencies = Currency.objects.all() categories = Category.objects.all() if 'cart' not in request.session: request.session['cart'] = list() cart_products = Product.objects.filter(id__in=request.session['cart']) cart_total_price = 0 for product in cart_products: cart_total_price = cart_total_price + product.product_price if request.method == "POST": form = OrderForm(request.POST) if form.is_valid(): order1 = form.save() print('form saved') order1.product.add() body = render_to_string("email.html", locals(), request) email = EmailMessage('Subject', body, to=['*****@*****.**']) email.content_subtype = 'html' email.send() messages.success(request, "Отлично! Ваше письмо отправлено!") else: messages.warning(request, "Упс! Проверьте заполнение полей!") else: form = OrderForm() return render(request, 'order_form.html', locals())
def cart(request): if request.method == 'POST': form = OrderForm(request.POST) if request.user.is_authenticated(): del(form.fields['captcha']) form.full_clean() if form.is_valid(): order = form.save(commit=False) order.save() data = form.cleaned_data # Заполняем у модели Order товары prds = ProductCost.objects.filter(id__in=data['products'].keys()) total_cost = 0 for prd in prds: op = OrderedProduct(product=prd, order=order, count=data['products'][prd.id]) op.save() total_cost += Decimal(prd.cost) * data['products'][prd.id] if total_cost < data['delivery'].free_from: total_cost += Decimal(data['delivery'].cost) order.amount = str(total_cost) order.save() return HttpResponseRedirect('/order/'+str(order.link)) else: form = OrderForm() products = [] if request.user.is_authenticated(): del(form.fields['captcha']) if 'products' in request.session.keys() and request.session['products']: products = ProductCost.objects.filter(id__in=request.session['products']) return render_to_response('cart.html', {'products': products, 'deliveries': Delivery.objects.all(),'order_form': form, 'max_products': range(1, settings.PDORUCT_MAX_ORDER+1)}, context_instance=RequestContext(request))
def order(request): c = get_common_context(request) if not request.user.is_authenticated(): return HttpResponseRedirect('/cart/') profile = request.user.get_profile() module = OrderDataFizForm if request.method == 'GET': form = module(instance=profile.get_orderdata(), initial={'fio': profile.fio}) orderform = OrderForm() if request.method == 'POST': form = module(request.POST, instance=profile.get_orderdata()) orderform = OrderForm(request.POST) if form.is_valid() and orderform.is_valid(): f = form.save(commit=False) f.user = request.user f.save() profile.fio = form['fio'].value() profile.save() of = orderform.save(commit=False) of.user = request.user of.savecommit() return HttpResponseRedirect('/order-ok/') c['form'] = form c['orderform'] = orderform return render_to_response('order.html', c, context_instance=RequestContext(request))
def make_order(request): user = request.user cart = Cart.objects.filter(owner=user).last() order_form = OrderForm(request.POST) # Form validation if order_form.is_valid(): phone = order_form['phone'].value() buy_type = order_form['buy_type'].value() address = order_form['address'].value() comments = order_form['comments'].value() # Setting default status of order status = 'Accepted' order = Order.objects.get_or_create(user=user, items=cart, phone=phone, address=address, buy_type=buy_type, comments=comments, status=status) if order[1]: order[0].save() new_cart = Cart.objects.create(owner=user) # Creating new cart for user after order new_cart.save() # Sending emails after making order server = smtplib.SMTP(MAIL_HOST, MAIL_PORT) server.ehlo() server.starttls() server.login(USERNAME, PASSWORD) # Txt of email message = 'Dear {0}! Your order has been accepted. Please wait until our manager will process ' \ 'your order. You will get an email notification after your order will be ready to ' \ 'deliver or pickup'.format(user.username) server.sendmail(USERNAME, user.email, message) server.quit() return render(request, 'order_final.html')
def order_cart(request): if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): subject = u'Заказ с сайта' recipients = [] try: recipients.extend(emails_list(request.settings.email)) except: recipients.append(settings.ADMINS[0][1]) cart = Cart(request, init=True) letter_context = form.cleaned_data letter_context.update({'site': request.settings.project}) order_text = render_to_string('order_info.txt', {'cart': cart}) letter_content = render_to_string('order_letter.txt', letter_context) letter_content += order_text send_mail(subject, letter_content, letter_context['email'] or recipients[0], recipients) success_message = u""" Благодарим за то, что Вы воспользовались услугами нашего Интернет-магазина. Ваша заявка принята в обработку и наш менеджер свяжется с Вами в ближайшее время для уточнения деталей. Мы будем благодарны Вам, если Вы оставите на нашем сайте свой отзыв о работе нашего Интернет-магазина. """ messages.add_message(request, messages.SUCCESS, success_message) cart.delete_all() return HttpResponseRedirect('') else: form = OrderForm() return render_to_response('cart_order.html', {'form': form}, context_instance=RequestContext(request))
def leave_bid(request): form = OrderForm(request.POST or None) context = {'form': form} if request.method == 'GET': return render(request, 'bid.html', context) else: if form.is_valid(): form.save() context['info'] = 'Order accepted' else: context['info'] = 'Invalid values' return render(request, 'bid.html', context)
def order_details(request, id): product = Mobile.objects.get(id=id) form = OrderForm(initial={"user": request.user, "product": product}) context = {} context["form"] = form if request.method == "POST": form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect("cart") else: form return render(request, "shop/order.html", context)
def orderadd(request): products = Product.objects.all() if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect('/orders') else: form = OrderForm() return render(request, 'shop/orderadd.html', { 'form': form, 'products': products })
def order(request): if request.POST: form = OrderForm(request.POST) if form.is_valid(): order = form.save() order.save() total_amount = int(((order.product_price * order.product_amount) + order.product_shipment_cost) * 100) return HttpResponseRedirect(get_payment_url(total_amount, order.id)) else: return direct_to_template(request, 'bestel-rustgever.html', extra_context={'error': True, 'form': form,}) else: form = OrderForm() return direct_to_template(request, 'bestel-rustgever.html', extra_context={'form': form})
def shop_order(request, template, extra_context=None, context_processors=None, template_loader=loader): o, create = Order.objects.get_or_create(session=request.shop_session, is_history=False) if request.method == 'POST': form = OrderForm(request.POST, instance=o) if form.is_valid(): form.save() if o.is_delivery_pay(): o.is_delivery = True o.cost_delivery = o.is_delivery_pay() o.is_history = True o.save() if o.email: domain = Site.objects.get_current().domain letter_send_mail( 'mail/order_accepted.html', _('Order is accepted. Order %(id)d in %(domain)s.') % { 'id': o.id, 'domain': domain }, [ o.email, ], { 'obj': o, 'domain': domain, }, ) return HttpResponseRedirect('/basket/order/thanks/') else: form = OrderForm() c = RequestContext(request, {'o': o, 'form': form}, context_processors) if extra_context: for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value t = template_loader.get_template(template) return HttpResponse(t.render(c))
def order(request): c = get_common_context(request) c['items'] = c['cart_working'].get_content() if request.method == 'GET': c['form'] = OrderForm() else: form = OrderForm(request.POST) if form.is_valid(): order = form.save(request=request) c['order'] = order return render_to_response('order_ok.html', c, context_instance=RequestContext(request)) else: c['form'] = form return render_to_response('order.html', c, context_instance=RequestContext(request))
def make_order_view(request): cart = check_cart(request) form = OrderForm(request.POST or None) context = { 'cart': cart, 'form': form, } if form.is_valid(): name = form.cleaned_data['name'] last_name = form.cleaned_data['last_name'] phone = form.cleaned_data['phone'] email = form.cleaned_data['email'] buying_type = form.cleaned_data['buying_type'] address = form.cleaned_data['address'] comments = form.cleaned_data['comments'] new_order = Order.objects.create(user=request.user, items=cart, total=cart.cart_total, first_name=name, last_name=last_name, phone=phone, email=email, address=address, buying_type=buying_type, comments=comments) # new_order = Order() # new_order.user = request.user # # new_order.items.add(cart) # new_order.items = cart # new_order.first_name = name # new_order.last_name = last_name # new_order.phone = phone # new_order.address = address # new_order.buying_type = buying_type # new_order.comments = comments # new_order.total = cart.cart_total # new_order.email = cart.email # new_order.save() del request.session['cart_id'] del request.session['total'] return HttpResponseRedirect(reverse('shop:confirmation')) return render(request, 'shop/order.html', context)
def cartorder(request): cart = request.session.get('cart').split(',') form = OrderForm(request.POST or None) success = None if form.is_valid(): order = form.save(commit = False) order.save() order.doors = Door.objects.filter(id__in = cart) order.save() request.session['cart'] = '' success = u'Ваш заказ удачно сохранен.' return render_to_response('shop/order.html', {'form': form, 'success': success}, context_instance = RequestContext(request))
def order(request): all_categories = Category.objects.all() cart = Cart(request) if request.method == "POST": user = User.objects.get(username=request.user.username) new_order = Order(user=user) form = OrderForm(request.POST, instance=new_order) if form.is_valid(): order = form.save() email_messaages = "你的购物内容如下:\n" for item in cart: OrderItem.objects.create(order=order, product=item.product, price=item.product.price, quantity=item.quantity) email_messaages += "\n" + "商品: {}, {}元, {}件".format( item.product, item.product.price, item.quantity) email_messaages += "\n以上共计{}元\nhttp://fanggaoshang.cn感谢你的订购!".format( cart.summary()) cart.clear() messages.add_message(request, messages.INFO, '订单已保存,我们会尽快处理') send_mail( "感谢你的订购", email_messaages, "迷你小电商<*****@*****.**>", [request.user.email], ) send_mail( "有人订购了产品", email_messaages, "迷你小电商<*****@*****.**>", ['*****@*****.**'], ) return redirect('/myorders/') else: form = OrderForm() return render(request, 'order.html', locals())
def shop_order(request, template, extra_context=None, context_processors=None, template_loader=loader): o, create = Order.objects.get_or_create(session=request.shop_session, is_history=False) if request.method == 'POST': form = OrderForm(request.POST, instance=o) if form.is_valid(): form.save() if o.is_delivery_pay(): o.is_delivery = True o.cost_delivery = o.is_delivery_pay() o.is_history = True o.save() if o.email: domain = Site.objects.get_current().domain letter_send_mail( 'mail/order_accepted.html', _('Order is accepted. Order %(id)d in %(domain)s.') % {'id':o.id, 'domain':domain}, [o.email,], {'obj':o, 'domain':domain,}, ) return HttpResponseRedirect('/basket/order/thanks/') else: form = OrderForm() c = RequestContext(request, {'o':o, 'form':form}, context_processors) if extra_context: for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value t = template_loader.get_template(template) return HttpResponse(t.render(c))
def add_order(req): if req.method == 'POST': if 'basket' not in req.session: return redirect('general') form = OrderForm(req.POST) if form.is_valid(): items_inv = req.session.get('basket') counts = req.session.get('item_count') l = [] s = 0 items = [x for x in zip(items_inv, counts)] for item, count in items: i = get_item(str(item)) l.append([i, count]) if type(i) == Share: s += i.price * count elif i.price_opt and count > 1: s += i.price_opt * count else: s += i.price * count items = pickle.dumps(items) context = dict() context['items'] = l order = form.save(commit=False) try: client = Client.objects.get(email=order.email) except Client.DoesNotExist: client = Client(email=order.email) client.save() finally: order.link_client = client context['pay'] = s tmp = None if client.discount > 0: tmp = client.discount tmp = s * tmp / 100 context['pay'] = str(s) + '- {0}% = '.format(client.discount) + str(round(s - tmp, 2)) order.items = items order.save() context['payment'] = Info.objects.get(pk=4) del req.session['basket'] del req.session['item_count'] tasks.message_send.delay(context, order) # connection = mail.get_connection() # email1 = mail.EmailMessage( # 'ELEKTROSWIT: Спасибо за покупку!', # ''.join(str(get_template('mail_order_usr/index.html').render(context))), # EMAIL_HOST_USER, # [order.email], # connection=connection # ) # context['to_admin'] = True # context['email'] = order.email # context['message'] = order.message # context['phone'] = order.phone # email2 = mail.EmailMessage( # 'ELEKTROSWIT: Поступил новый заказ!', # ''.join(str(get_template('mail_order_usr/index.html').render(context))), # EMAIL_HOST_USER, # ['*****@*****.**'], # connection=connection # ) # email1.content_subtype = 'html' # email2.content_subtype = 'html' # email1.send(fail_silently=True) # email2.send(fail_silently=True) # connection.close() ###### # send_mail( # 'ELEKTROSWIT: Спасибо за покупку!', # ' ', # '*****@*****.**', # [order.email], # fail_silently=True, # html_message=get_template('mail_order_usr/index.html').render(context) # ) # send_mail( # 'ELEKTROSWIT: Поступил новый заказ!', # ' ', # '*****@*****.**', # ['*****@*****.**'], # fail_silently=True, # html_message=get_template('mail_order_usr/index.html').render(context) # ) return redirect('general') else: return show_basket(req, form)
def post(self, request, *args, **kwargs): def _get_total_price(ordered_products): total_price = 0 for ordered_product in ordered_products: total_price += ordered_product.total return total_price if request.user.is_authenticated: cart = CartAuth(request) else: cart = Cart(request) order_form = OrderForm(request.POST) if order_form.is_valid(): fullname = order_form.cleaned_data['fullname'] email = order_form.cleaned_data['email'] phone = order_form.cleaned_data['phone'] user = None if request.user.is_authenticated: user = request.user elif User.objects.get(username=email).exists(): return redirect(reverse('account:login')) else: password = User.objects.make_random_password() user = User.objects.create_user(email, email, password) profile = Profile(user=user, phone=phone) profile.save() user.last_name = fullname postcode = order_form.cleaned_data.get('postcode') region = order_form.cleaned_data.get('region') area = order_form.cleaned_data.get('area') city = order_form.cleaned_data.get('city') street = order_form.cleaned_data.get('street') house = order_form.cleaned_data.get('house') building = order_form.cleaned_data.get('building') apartment = order_form.cleaned_data.get('apartment') comment = order_form.cleaned_data.get('comment') payment_type = order_form.cleaned_data.get('payment_type') entity_name = order_form.cleaned_data.get('entity_name') entity_inn = order_form.cleaned_data.get('entity_inn') entity_kpp = order_form.cleaned_data.get('entity_kpp') delivery = None entity = None if postcode: delivery = Delivery(postcode=postcode, region=region, area=area, city=city, street=street, house=house, building=building, apartment=apartment, comment=comment) delivery.save() if entity_name: entity = Entity(title=entity_name, inn=entity_inn, kpp=entity_kpp) entity.save() order = Order(delivery=delivery, user=user, entity=entity) order.save() products = tuple(cart.get()) print(tuple(products), 'ORDER PRODUCTS FOR CREATE') ordered_products = OrderedProducts.objects.bulk_create( OrderedProducts(order=order, product=product, count=product.count, total=product.get_discount_price() * int(product.count)) for product in products) if payment_type in ('bank', 'bill', 'receipt'): payment = Payment(total=_get_total_price(ordered_products), _type=self.payment_type_crutch[payment_type]) payment.save() order.payment = payment order.save() return redirect(reverse('account:ProfileOrders')) return redirect(reverse('account:ProfileOrders'))