本文整理汇总了Python中orders.models.Order.save方法的典型用法代码示例。如果您正苦于以下问题:Python Order.save方法的具体用法?Python Order.save怎么用?Python Order.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类orders.models.Order
的用法示例。
在下文中一共展示了Order.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save
# 需要导入模块: from orders.models import Order [as 别名]
# 或者: from orders.models.Order import save [as 别名]
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
示例2: do
# 需要导入模块: from orders.models import Order [as 别名]
# 或者: from orders.models.Order import save [as 别名]
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()
示例3: get
# 需要导入模块: from orders.models import Order [as 别名]
# 或者: from orders.models.Order import save [as 别名]
def get(self, request, *args, **kwargs ):
get_data = super(CheckoutView, self).get(request, *args, **kwargs)
cart = self.get_object()
user_checkout_id = request.session.get("user_checkout_id")
if user_checkout_id != None:
user_checkout = UserCheckout.objects.get(id=user_checkout_id)
billing_address_id = request.session.get("billing_address_id")
shipping_address_id = request.session.get("shipping_address_id")
if billing_address_id == None or shipping_address_id == None:
return redirect('order_address')
else:
billing_address = UserAddress.objects.get(id=billing_address_id)
shipping_address = UserAddress.objects.get(id=shipping_address_id)
try:
new_order_id = request.session['order_id']
new_order = Order.objects.get(id=new_order_id)
except:
new_order = Order()
request.session["order_id"] = new_order.id
# new_order.cart = cart
new_order.user = user_checkout
new_order.billing_address = billing_address
new_order.shipping_address = shipping_address
new_order.save()
return get_data
示例4: test_payment_failed_flow
# 需要导入模块: from orders.models import Order [as 别名]
# 或者: from orders.models.Order import save [as 别名]
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'
示例5: new_order
# 需要导入模块: from orders.models import Order [as 别名]
# 或者: from orders.models.Order import save [as 别名]
def new_order(request, pk):
template = 'pos/new_order.html'
form = OrderForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
table_order = Order.objects.filter(table=pk)
latest = table_order.latest('created')
if latest.paid == True:
order = Order()
else:
order = latest
order.number = Order.objects.count() + 1
order.table = Table.objects.get(number=pk)
order.paid = False
order.save()
orderitem = OrderItem()
product = form.cleaned_data.get('product')
orderitem.product = Product.objects.get(title=product)
orderitem.order = order
orderitem.table = Table.objects.get(number=pk)
orderitem.quantity = form.cleaned_data.get('quantity')
orderitem.total_price = orderitem.quantity * orderitem.product.unit_price
orderitem.discount = form.cleaned_data.get('discount')
orderitem.notes = form.cleaned_data.get('notes')
orderitem.save()
return redirect('/table/' + pk)
context = {'form': form}
return render(request, template, context)
示例6: test_payment_get_paid
# 需要导入模块: from orders.models import Order [as 别名]
# 或者: from orders.models.Order import save [as 别名]
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])
示例7: finalize
# 需要导入模块: from orders.models import Order [as 别名]
# 或者: from orders.models.Order import save [as 别名]
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')
示例8: handle
# 需要导入模块: from orders.models import Order [as 别名]
# 或者: from orders.models.Order import save [as 别名]
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.")
示例9: create_order
# 需要导入模块: from orders.models import Order [as 别名]
# 或者: from orders.models.Order import save [as 别名]
def create_order(request,cart, delivery=None):
subtotal = cart.total_price
order = Order()
order.user = request.user
delivery = Delivery.objects.all()[0]
order.delivery = delivery
order.total = subtotal + Decimal(order.delivery.price)
order.save()
for pro in cart:
line = OrderLine()
line.order = order
line.product = pro.item
line.quantity = pro.quantity
if pro.color:
line.color = Color.objects.get(pk=pro.color)
if pro.size:
line.size = Size.objects.get(pk=pro.size)
line.line_price = pro.item.total_price() * pro.quantity
line.save()
request.session['order_pk'] = order.pk
return order
示例10: test_failure_order_additional_validation
# 需要导入模块: from orders.models import Order [as 别名]
# 或者: from orders.models.Order import save [as 别名]
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)
示例11: create_new_order
# 需要导入模块: from orders.models import Order [as 别名]
# 或者: from orders.models.Order import save [as 别名]
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
示例12: submit
# 需要导入模块: from orders.models import Order [as 别名]
# 或者: from orders.models.Order import save [as 别名]
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)
示例13: process_order
# 需要导入模块: from orders.models import Order [as 别名]
# 或者: from orders.models.Order import save [as 别名]
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
# 需要导入模块: from orders.models import Order [as 别名]
# 或者: from orders.models.Order import save [as 别名]
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
# 需要导入模块: from orders.models import Order [as 别名]
# 或者: from orders.models.Order import save [as 别名]
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