本文整理汇总了Python中orders.models.Order类的典型用法代码示例。如果您正苦于以下问题:Python Order类的具体用法?Python Order怎么用?Python Order使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Order类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: submit
def submit(request):
message = 'Something went wrong :('
if request.is_ajax():
if request.method == 'POST':
# Here we can access the POST data
itemlist = simplejson.loads(request.raw_post_data)
o = None
#loops through the provided json
for item in itemlist:
if item['value']:
if int(item['value']) > 0:
#checks if the order exists yet
if o == None:
o = Order(tendered="1000", table="1")
o.save()
c = Content(order= o, quantity= item['value'])
#determines the type of the drink
if str(item['name'])[:1] == "d":
c.takeaway = False
elif str(item['name'])[:1] == "t":
c.takeaway = True
c.beverage = Beverage.objects.get(pk= str(item['name'])[2::])
c.save()
cache.delete_many(['orders_current_orders', 'orders_current_contents'])
message = "XHR Complete"
return HttpResponse(message)
示例2: test_payment_failed_flow
def test_payment_failed_flow(self):
Payment = apps.get_model('getpaid', 'Payment')
order = Order(name='Test PLN order', total='20.00', currency='PLN')
order.save()
payment = Payment(pk=23, order=order, amount=order.total, currency=order.currency,
backend='getpaid.backends.payu_rest')
payment.save(force_insert=True)
confirm_url = "http://localhost" + reverse('getpaid:payu_rest:confirm')
# Fake PayU pings on confirmation URL
# PENDING
data_1 = b"""{"order":{"orderId":"6N73GWVD9P180712GUEST000P01","extOrderId":"23","orderCreateDate":"2018-07-12T14:55:18.209+02:00","notifyUrl":"http://getpaid.requestcatcher.com/","customerIp":"127.0.0.1","merchantPosId":"123456","description":"Test Payment","currencyCode":"PLN","totalAmount":"2000","status":"PENDING","products":[{"name":"Order #123456 from example.com","unitPrice":"2000","quantity":"1"}]},"properties":[{"name":"PAYMENT_ID","value":"73543299"}]}"""
with mock.patch("getpaid.backends.payu_rest.views.get_request_body", return_value=data_1):
self.client.post(confirm_url,
data={},
**{
"HTTP_OPENPAYU_SIGNATURE": "sender=checkout;signature=f5482f0bca32c3094f6840637ae0c52f;algorithm=MD5;content=DOCUMENT"
})
payment.refresh_from_db()
assert payment.status == 'in_progress'
# FAILED
data_2 = b"""{"order":{"orderId":"6N73GWVD9P180712GUEST000P01","extOrderId":"23","orderCreateDate":"2018-07-12T14:55:18.209+02:00","notifyUrl":"http://getpaid.requestcatcher.com/","customerIp":"127.0.0.1","merchantPosId":"123456","description":"Test Payment","currencyCode":"PLN","totalAmount":"2000","status":"CANCELED","products":[{"name":"Order #123456 from example.com","unitPrice":"2000","quantity":"1"}]},"properties":[{"name":"PAYMENT_ID","value":"73543299"}]}"""
with mock.patch("getpaid.backends.payu_rest.views.get_request_body", return_value=data_2):
self.client.post(confirm_url,
data={},
**{
"HTTP_OPENPAYU_SIGNATURE": "sender=checkout;signature=c69bc143125a7423e5fdfa6714db9753;algorithm=MD5;content=DOCUMENT"
})
payment.refresh_from_db()
assert payment.status == 'cancelled'
示例3: handle
def handle(self, *args, **options):
logger = logging.getLogger()
steam_handler = logging.StreamHandler()
steam_handler.setLevel(logging.DEBUG)
logger.addHandler(steam_handler)
try:
request = urllib2.urlopen("http://test.ecommerce.io/orders-test.xml")
tree = ET.parse(request)
except:
raise CommandError('Xml file is not valid')
orders = tree.find("orders")
for item in orders.getiterator('order'):
if ((item.find('marketplace').text) is not None)\
and(item.find('order_purchase_date').text is not None)\
and(item.find('order_amount').text is not None)\
and(item.find('order_currency').text is not None)\
and(item.find('order_id').text is not None):
marketplace = item.find('marketplace')
order_purchase_date = item.find('order_purchase_date')
order_amount = item.find('order_amount')
order_currency = item.find('order_currency')
order_id = item.find('order_id')
# add and save a new order
new_order = Order(marketplace=marketplace.text,
order_purchase_date=order_purchase_date.text,
order_amount=order_amount.text,
order_currency=order_currency.text,
order_id=order_id.text)
new_order.save()
else:
logger.warning("A required argument is missing"
" for one order, please look at your xml file.")
示例4: test_payment_get_paid
def test_payment_get_paid(self, mock_Request):
Payment = apps.get_model('getpaid', 'Payment')
order = Order(name='Test PLN order', total='123.45', currency='PLN')
order.save()
payment = Payment(pk=99, order=order, amount=order.total, currency=order.currency,
backend='getpaid.backends.payu')
payment.save(force_insert=True)
payment = Payment.objects.get(
pk=99) # this line is because django bug https://code.djangoproject.com/ticket/5903
processor = getpaid.backends.payu.PaymentProcessor(payment)
processor.get_payment_status(u'99:1342616247.41')
self.assertEqual(payment.status, u'paid')
self.assertNotEqual(payment.paid_on, None)
self.assertNotEqual(payment.amount_paid, Decimal('0'))
url = 'https://secure.payu.com/paygw/UTF/Payment/get/txt'
callargs = mock_Request.call_args_list
self.assertEqual(url, callargs[0][0][0])
if six.PY3:
self.assertIsInstance(callargs[0][0][1], bytes)
self.assertTrue(b'pos_id=123456789' in callargs[0][0][1])
self.assertTrue(b'session_id=99%3A1342616247.41' in callargs[0][0][1])
else:
self.assertIsInstance(callargs[0][0][1], str)
self.assertTrue('pos_id=123456789' in callargs[0][0][1])
self.assertTrue('session_id=99%3A1342616247.41' in callargs[0][0][1])
示例5: finalize
def finalize(request):
if request.method == 'POST':
if request.user.is_authenticated():
print request.POST
order = Order(first_name=request.POST['first_name'], last_name=request.POST['last_name'],
street=request.POST['street'], number=request.POST['number'], zip=request.POST['zip'], \
city=request.POST['city'], price=request.POST['summary'], withdrawtype=request.POST['collection'], \
user=request.user, paid=0, \
phone=request.POST['phone'], title=request.POST['title'])
order.save()
for book in request.POST.getlist("book[]"):
tmpbook = Book.objects.get(id=book)
orderedbook = OrderedBook(title=tmpbook.title, author=tmpbook.author, publisher=tmpbook.publisher, price=tmpbook.price, returned=0, book=tmpbook, order=order)
orderedbook.save()
request.session["message"] = u"Zamówienie zostało złożone. Zostanie zrealizowane niezwłocznie po zaksięgowaniu wpłaty"
request.session["message_context"] = "success"
return HttpResponseRedirect('/')
else:
request.session["message"] = u"Przed złożeniem zamówienia zaloguj się lub załóż konto"
request.session["message_context"] = "danger"
return HttpResponseRedirect('/users/authenticate')
else:
request.session["message"] = u"Zamówienie nie zostało wysłane poprawnie"
request.session["message_context"] = "danger"
return HttpResponseRedirect('/orders/checkout')
示例6: create_new_order
def create_new_order(checkout_form):
"""
Создает новый заказ, используя информацию о форме чекаута, корзине и пользователе
:param checkout_form:
:param cart:
:param user:
:return:
"""
data = checkout_form.cleaned_data
cart_summary = checkout_form.cart_summary
shipping_method = methods[data['shipment']](cart=checkout_form.cart)
payment_method = gateways[data['payment']]()
order = Order(cart=checkout_form.cart,
user=checkout_form.user,
shipping_method=data['shipment'],
payment_method=data['payment'],
order_status=shipping_method.order_status,
payment_status=payment_method.payment_status,
shipping_price=cart_summary['shipping_price'],
shipping_address=data.get('address', ''),
phone=data.get('phone', ''),
email=data['email'],
contact_person=data['first_name'] + ' ' + data['last_name'],
discount=cart_summary['discount']
)
order.save()
# Сформировать и отправить письмо с заказом
send_new_order_email(data['email'], order)
# ToDo Письмо администраторам
return order
示例7: test_failure_order_additional_validation
def test_failure_order_additional_validation(self):
"""
Tests if HTTP304 when order additional validation signal raises
ValidationError exception.
"""
def custom_validation_listener(sender=None, request=None, order=None,
backend=None, **kwargs):
raise ValidationError("BOOM!")
suid = 'test-order_additional_validation'
signals.order_additional_validation.connect(custom_validation_listener,
dispatch_uid=suid)
order = Order(name='Test order custom validation',
total=100,
currency='PLN')
order.save()
try:
url = reverse('getpaid:new-payment', kwargs={'currency': 'PLN'})
data = {'order': order.pk, 'backend': 'getpaid.backends.payu'}
response = self.client.post(url, data)
self.assertEqual(response.status_code, 403)
finally:
signals.order_additional_validation.disconnect(dispatch_uid=suid)
示例8: save
def save(self, user, commit=True):
from django.contrib.contenttypes.models import ContentType
#
booking = super(BookingForm, self).save(commit=False)
booking.booked_by = user
open_order_list = Order.objects.open_order(user=user)
if open_order_list:
order = open_order_list[0]
if commit:
booking.save()
# Add to open order
if not open_order_list:
order = Order(ordered_by=user)
order.save()
order_item = OrderItem(
order=order,
description=booking.price.__unicode__(),
value=(booking.price.value*booking.quantity),
vat=booking.price.vat,
content_type=ContentType.objects.get_for_model(booking),
object_id=booking.id
)
order_item.save()
return booking
示例9: do
def do(self):
last_order = Order.objects.all().order_by('pk').last()
last_order.open = False
last_order.save()
o = Order(date=next_thursday())
o.save()
示例10: test_order_accept
def test_order_accept(self):
order_test = Order(client_phone=8432424,
type=Order.TYPE_DINNER_WAGON,
state=Order.STATE_DONE,
order_date=date(2014, 12, 12),
execute_date=datetime(2014, 12, 12).date())
order_test.accept()
self.assertEqual(order_test.state, Order.STATE_IN_PROGRESS)
示例11: test_order_perform
def test_order_perform(self):
order_test = Order(client_phone=8432424,
type=Order.TYPE_DINNER_WAGON,
state=Order.STATE_DONE,
order_date=date(2014, 12, 12),
execute_date=datetime(2014, 12, 12).date(),
dinner_wagon=DinnerWagon(seats=2))
order_test.perform()
self.assertEqual(order_test.state, Order.STATE_DONE)
示例12: test_order_make
def test_order_make(self):
order_test = Order(client_phone=8432424,
type=Order.TYPE_DINNER_WAGON,
state=Order.STATE_DONE,
order_date=date(2014, 12, 12),
execute_date=datetime(2014, 12, 12).date())
order_test.make()
self.assertEqual(order_test.state.__str__(), '4', 'State of order is not equal')
self.assertEqual(order_test.type, Order.TYPE_DINNER_WAGON)
示例13: process_order
def process_order(request):
context = RequestContext(request)
user = request.user
increment_clicks(user)
profile = get_associated_profile(user)
cart = get_cart(profile)
items_to_package = []
total_price = 0
for item in CartItem.objects.all():
if item.cart == cart:
items_to_package.append(item.item)
total_price = total_price + item.item.price
entry_id = request.POST.get("entry_id")
entry = Entry.objects.get(id=entry_id)
new_order = Order(
user_profile=profile,
restaurant=profile.restaurant,
total=total_price,
entry=entry,
status="PDG",
order_success=False,
order_rating=0,
)
new_order.save()
order_dict = {}
for item in items_to_package:
if item.id in order_dict.keys():
order_dict[item.id] = order_dict[item.id] + 1
else:
order_dict[item.id] = 1
order_items = []
for key in order_dict.keys():
item = Item.objects.get(id=key)
quantity = order_dict[key]
new_order_item = OrderItem(item=item, order=new_order, quantity=quantity)
new_order_item.save()
order_items.append(new_order_item)
# cart.delete()
# print order_dict.keys()
cart_id = cart.id
print cart.id
return render_to_response(
"confirm.html",
{"total_price": total_price, "user": user, "profile": profile, "order_items": order_items, "cart_id": cart_id},
context,
)
示例14: test_creating_a_new_order_and_saving
def test_creating_a_new_order_and_saving(self):
order = Order()
order.ticket = 'Ticket 1234'
#
order.save()
all_orders = Order.objects.all()
self.assertEqual(len(all_orders), 1)
only_order = all_orders[0]
self.assertEqual(only_order,order)
self.assertEqual(only_order.ticket, order.ticket)
示例15: save
def save(self, event, price, user, commit=True):
from django.contrib.contenttypes.models import ContentType
#
booking = super(BookingForm, self).save(commit=False)
booking.booked_by = user
booking.event = event
booking.price = price
total_booked = 0
open_order_list = Order.objects.open_order(user=user)
if open_order_list:
order = open_order_list[0]
for item in order.orderitem_set.all():
total_booked += item.content_object.quantity
if not(event.pricing_set.all().filter(online_book=True)
and not event.fully_booked):
raise ValidationError(
_('This event is fully booked'),
code='Fully Booked'
)
commit = False
elif event.num_spaces < (booking.quantity + total_booked):
places = booking.quantity + total_booked
raise ValidationError(
_('Not enough spaces for %(places)s people.'),
code='No Space',
params={'places': places},
)
commit = False
if commit:
booking.save()
# Add to open order
if not open_order_list:
order = Order(ordered_by=user)
order.save()
order_item = OrderItem(
order=order,
description=event.__unicode__(),
value=(price.value*booking.quantity),
vat=price.vat,
content_type=ContentType.objects.get_for_model(booking),
object_id=booking.id
)
order_item.save()
return booking