You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

views.py 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. import logging
  2. from django.http import Http404, HttpResponseRedirect, HttpResponseBadRequest
  3. from django.core.urlresolvers import reverse, reverse_lazy
  4. from django.contrib import messages
  5. from django.contrib.auth import login
  6. from django.db.models import get_model
  7. from django.utils.translation import ugettext as _
  8. from django.views.generic import DetailView, TemplateView, FormView, \
  9. DeleteView, UpdateView, CreateView
  10. from oscar.apps.customer.utils import normalise_email
  11. from oscar.apps.shipping.methods import NoShippingRequired
  12. from oscar.core.loading import get_class, get_classes
  13. ShippingAddressForm, GatewayForm = get_classes('checkout.forms', ['ShippingAddressForm', 'GatewayForm'])
  14. OrderTotalCalculator = get_class('checkout.calculators', 'OrderTotalCalculator')
  15. CheckoutSessionData = get_class('checkout.utils', 'CheckoutSessionData')
  16. pre_payment, post_payment = get_classes('checkout.signals', ['pre_payment', 'post_payment'])
  17. OrderNumberGenerator, OrderCreator = get_classes('order.utils', ['OrderNumberGenerator', 'OrderCreator'])
  18. UserAddressForm = get_class('address.forms', 'UserAddressForm')
  19. Repository = get_class('shipping.repository', 'Repository')
  20. AccountAuthView = get_class('customer.views', 'AccountAuthView')
  21. RedirectRequired, UnableToTakePayment, PaymentError = get_classes(
  22. 'payment.exceptions', ['RedirectRequired', 'UnableToTakePayment', 'PaymentError'])
  23. UnableToPlaceOrder = get_class('order.exceptions', 'UnableToPlaceOrder')
  24. OrderPlacementMixin = get_class('checkout.mixins', 'OrderPlacementMixin')
  25. CheckoutSessionMixin = get_class('checkout.session', 'CheckoutSessionMixin')
  26. Order = get_model('order', 'Order')
  27. ShippingAddress = get_model('order', 'ShippingAddress')
  28. CommunicationEvent = get_model('order', 'CommunicationEvent')
  29. PaymentEventType = get_model('order', 'PaymentEventType')
  30. PaymentEvent = get_model('order', 'PaymentEvent')
  31. UserAddress = get_model('address', 'UserAddress')
  32. Basket = get_model('basket', 'Basket')
  33. Email = get_model('customer', 'Email')
  34. CommunicationEventType = get_model('customer', 'CommunicationEventType')
  35. # Standard logger for checkout events
  36. logger = logging.getLogger('oscar.checkout')
  37. class IndexView(CheckoutSessionMixin, FormView):
  38. """
  39. First page of the checkout. We prompt user to either sign in, or
  40. to proceed as a guest (where we still collect their email address).
  41. """
  42. template_name = 'checkout/gateway.html'
  43. form_class = GatewayForm
  44. success_url = reverse_lazy('checkout:shipping-address')
  45. def get(self, request, *args, **kwargs):
  46. # We redirect immediately to shipping address stage if the user is
  47. # signed in
  48. if request.user.is_authenticated():
  49. return self.get_success_response()
  50. return super(IndexView, self).get(request, *args, **kwargs)
  51. def get_form_kwargs(self):
  52. kwargs = super(IndexView, self).get_form_kwargs()
  53. email = self.checkout_session.get_guest_email()
  54. if email:
  55. kwargs['initial'] = {
  56. 'username': email,
  57. }
  58. return kwargs
  59. def form_valid(self, form):
  60. if form.is_guest_checkout() or form.is_new_account_checkout():
  61. email = form.cleaned_data['username']
  62. self.checkout_session.set_guest_email(email)
  63. if form.is_new_account_checkout():
  64. messages.info(
  65. self.request,
  66. _("Create your account and then you will be redirected "
  67. "back to the checkout process"))
  68. self.success_url = "%s?next=%s&email=%s" % (
  69. reverse('customer:register'),
  70. reverse('checkout:shipping-address'),
  71. email
  72. )
  73. else:
  74. user = form.get_user()
  75. login(self.request, user)
  76. return self.get_success_response()
  77. def get_success_response(self):
  78. return HttpResponseRedirect(self.get_success_url())
  79. def get_success_url(self):
  80. return self.success_url
  81. # ================
  82. # SHIPPING ADDRESS
  83. # ================
  84. class ShippingAddressView(CheckoutSessionMixin, FormView):
  85. """
  86. Determine the shipping address for the order.
  87. The default behaviour is to display a list of addresses from the users's
  88. address book, from which the user can choose one to be their shipping address.
  89. They can add/edit/delete these USER addresses. This address will be
  90. automatically converted into a SHIPPING address when the user checks out.
  91. Alternatively, the user can enter a SHIPPING address directly which will be
  92. saved in the session and later saved as ShippingAddress model when the order
  93. is sucessfully submitted.
  94. """
  95. template_name = 'checkout/shipping_address.html'
  96. form_class = ShippingAddressForm
  97. def get(self, request, *args, **kwargs):
  98. # Check that the user's basket is not empty
  99. if request.basket.is_empty:
  100. messages.error(request, _("You need to add some items to your basket to checkout"))
  101. return HttpResponseRedirect(reverse('basket:summary'))
  102. # Check that guests have entered an email address
  103. if not request.user.is_authenticated() and not self.checkout_session.get_guest_email():
  104. messages.error(request, _("Please either sign in or enter your email address"))
  105. return HttpResponseRedirect(reverse('checkout:index'))
  106. # Check to see that a shipping address is actually required. It may not be if
  107. # the basket is purely downloads
  108. if not request.basket.is_shipping_required():
  109. messages.info(request, _("Your basket does not require a shipping address to be submitted"))
  110. return HttpResponseRedirect(self.get_success_url())
  111. return super(ShippingAddressView, self).get(request, *args, **kwargs)
  112. def get_initial(self):
  113. return self.checkout_session.new_shipping_address_fields()
  114. def get_context_data(self, **kwargs):
  115. kwargs = super(ShippingAddressView, self).get_context_data(**kwargs)
  116. if self.request.user.is_authenticated():
  117. # Look up address book data
  118. kwargs['addresses'] = self.get_available_addresses()
  119. return kwargs
  120. def get_available_addresses(self):
  121. return UserAddress._default_manager.filter(user=self.request.user).order_by('-is_default_for_shipping')
  122. def post(self, request, *args, **kwargs):
  123. # Check if a shipping address was selected directly (eg no form was filled in)
  124. if self.request.user.is_authenticated() and 'address_id' in self.request.POST:
  125. address = UserAddress._default_manager.get(pk=self.request.POST['address_id'],
  126. user=self.request.user)
  127. action = self.request.POST.get('action', None)
  128. if action == 'ship_to':
  129. # User has selected a previous address to ship to
  130. self.checkout_session.ship_to_user_address(address)
  131. return HttpResponseRedirect(self.get_success_url())
  132. elif action == 'delete':
  133. # Delete the selected address
  134. address.delete()
  135. messages.info(self.request, _("Address deleted from your address book"))
  136. return HttpResponseRedirect(reverse('checkout:shipping-method'))
  137. else:
  138. return HttpResponseBadRequest()
  139. else:
  140. return super(ShippingAddressView, self).post(request, *args, **kwargs)
  141. def form_valid(self, form):
  142. # Store the address details in the session and redirect to next step
  143. self.checkout_session.ship_to_new_address(form.clean())
  144. return super(ShippingAddressView, self).form_valid(form)
  145. def get_success_url(self):
  146. return reverse('checkout:shipping-method')
  147. class UserAddressUpdateView(CheckoutSessionMixin, UpdateView):
  148. """
  149. Update a user address
  150. """
  151. template_name = 'checkout/user_address_form.html'
  152. form_class = UserAddressForm
  153. def get_queryset(self):
  154. return self.request.user.addresses.all()
  155. def get_form_kwargs(self):
  156. kwargs = super(UserAddressUpdateView, self).get_form_kwargs()
  157. kwargs['user'] = self.request.user
  158. return kwargs
  159. def get_success_url(self):
  160. messages.info(self.request, _("Address saved"))
  161. return reverse('checkout:shipping-address')
  162. class UserAddressDeleteView(CheckoutSessionMixin, DeleteView):
  163. """
  164. Delete an address from a user's addressbook.
  165. """
  166. template_name = 'checkout/user_address_delete.html'
  167. def get_queryset(self):
  168. return self.request.user.addresses.all()
  169. def get_success_url(self):
  170. messages.info(self.request, _("Address deleted"))
  171. return reverse('checkout:shipping-address')
  172. # ===============
  173. # Shipping method
  174. # ===============
  175. class ShippingMethodView(CheckoutSessionMixin, TemplateView):
  176. """
  177. View for allowing a user to choose a shipping method.
  178. Shipping methods are largely domain-specific and so this view
  179. will commonly need to be subclassed and customised.
  180. The default behaviour is to load all the available shipping methods
  181. using the shipping Repository. If there is only 1, then it is
  182. automatically selected. Otherwise, a page is rendered where
  183. the user can choose the appropriate one.
  184. """
  185. template_name = 'checkout/shipping_methods.html'
  186. def get(self, request, *args, **kwargs):
  187. # Check that the user's basket is not empty
  188. if request.basket.is_empty:
  189. messages.error(request, _("You need to add some items to your basket to checkout"))
  190. return HttpResponseRedirect(reverse('basket:summary'))
  191. # Check that shipping is required at all
  192. if not request.basket.is_shipping_required():
  193. self.checkout_session.use_shipping_method(NoShippingRequired().code)
  194. return self.get_success_response()
  195. # Check that shipping address has been completed
  196. if not self.checkout_session.is_shipping_address_set():
  197. messages.error(request, _("Please choose a shipping address"))
  198. return HttpResponseRedirect(reverse('checkout:shipping-address'))
  199. # Save shipping methods as instance var as we need them both here
  200. # and when setting the context vars.
  201. self._methods = self.get_available_shipping_methods()
  202. if len(self._methods) == 0:
  203. # No shipping methods available for given address
  204. messages.warning(request, _("Shipping is not available for your chosen address - please choose another"))
  205. return HttpResponseRedirect(reverse('checkout:shipping-address'))
  206. elif len(self._methods) == 1:
  207. # Only one shipping method - set this and redirect onto the next step
  208. self.checkout_session.use_shipping_method(self._methods[0].code)
  209. return self.get_success_response()
  210. # Must be more than one available shipping method, we present them to
  211. # the user to make a choice.
  212. return super(ShippingMethodView, self).get(request, *args, **kwargs)
  213. def get_context_data(self, **kwargs):
  214. kwargs = super(ShippingMethodView, self).get_context_data(**kwargs)
  215. kwargs['methods'] = self._methods
  216. return kwargs
  217. def get_available_shipping_methods(self):
  218. """
  219. Returns all applicable shipping method objects
  220. for a given basket.
  221. """
  222. # Shipping methods can depend on the user, the contents of the basket
  223. # and the shipping address. I haven't come across a scenario that doesn't
  224. # fit this system.
  225. return Repository().get_shipping_methods(self.request.user, self.request.basket,
  226. self.get_shipping_address())
  227. def post(self, request, *args, **kwargs):
  228. # Need to check that this code is valid for this user
  229. method_code = request.POST.get('method_code', None)
  230. is_valid = False
  231. for method in self.get_available_shipping_methods():
  232. if method.code == method_code:
  233. is_valid = True
  234. if not is_valid:
  235. messages.error(request, _("Your submitted shipping method is not permitted"))
  236. return HttpResponseRedirect(reverse('checkout:shipping-method'))
  237. # Save the code for the chosen shipping method in the session
  238. # and continue to the next step.
  239. self.checkout_session.use_shipping_method(method_code)
  240. return self.get_success_response()
  241. def get_success_response(self):
  242. return HttpResponseRedirect(reverse('checkout:payment-method'))
  243. # ==============
  244. # Payment method
  245. # ==============
  246. class PaymentMethodView(CheckoutSessionMixin, TemplateView):
  247. """
  248. View for a user to choose which payment method(s) they want to use.
  249. This would include setting allocations if payment is to be split
  250. between multiple sources.
  251. """
  252. def get(self, request, *args, **kwargs):
  253. # Check that the user's basket is not empty
  254. if request.basket.is_empty:
  255. messages.error(request, _("You need to add some items to your basket to checkout"))
  256. return HttpResponseRedirect(reverse('basket:summary'))
  257. shipping_required = request.basket.is_shipping_required()
  258. # Check that shipping address has been completed
  259. if shipping_required and not self.checkout_session.is_shipping_address_set():
  260. messages.error(request, _("Please choose a shipping address"))
  261. return HttpResponseRedirect(reverse('checkout:shipping-address'))
  262. # Check that shipping method has been set
  263. if shipping_required and not self.checkout_session.is_shipping_method_set():
  264. messages.error(request, _("Please choose a shipping method"))
  265. return HttpResponseRedirect(reverse('checkout:shipping-method'))
  266. return self.get_success_response()
  267. def get_success_response(self):
  268. return HttpResponseRedirect(reverse('checkout:payment-details'))
  269. # ================
  270. # Order submission
  271. # ================
  272. class PaymentDetailsView(OrderPlacementMixin, TemplateView):
  273. """
  274. For taking the details of payment and creating the order
  275. The class is deliberately split into fine-grained methods, responsible for
  276. only one thing. This is to make it easier to subclass and override just
  277. one component of functionality.
  278. All projects will need to subclass and customise this class.
  279. """
  280. template_name = 'checkout/payment_details.html'
  281. template_name_preview = 'checkout/preview.html'
  282. preview = False
  283. def get(self, request, *args, **kwargs):
  284. error_response = self.get_error_response()
  285. if error_response:
  286. return error_response
  287. return super(PaymentDetailsView, self).get(request, *args, **kwargs)
  288. def post(self, request, *args, **kwargs):
  289. """
  290. This method is designed to be overridden by subclasses which will
  291. validate the forms from the payment details page. If the forms are
  292. valid then the method can call submit()
  293. """
  294. error_response = self.get_error_response()
  295. if error_response:
  296. return error_response
  297. if self.preview:
  298. # We use a custom parameter to indicate if this is an attempt to
  299. # place an order. Without this, we assume a payment form is being
  300. # submitted from the payment-details page
  301. if request.POST.get('action', '') == 'place_order':
  302. return self.submit(request.basket)
  303. return self.render_preview(request)
  304. # Posting to payment-details isn't the right thing to do
  305. return self.get(request, *args, **kwargs)
  306. def get_error_response(self):
  307. # Check that the user's basket is not empty
  308. if self.request.basket.is_empty:
  309. messages.error(self.request, _("You need to add some items to your basket to checkout"))
  310. return HttpResponseRedirect(reverse('basket:summary'))
  311. shipping_required = self.request.basket.is_shipping_required()
  312. # Check that shipping address has been completed
  313. if shipping_required and not self.checkout_session.is_shipping_address_set():
  314. messages.error(self.request, _("Please choose a shipping address"))
  315. return HttpResponseRedirect(reverse('checkout:shipping-address'))
  316. # Check that shipping method has been set
  317. if shipping_required and not self.checkout_session.is_shipping_method_set():
  318. messages.error(self.request, _("Please choose a shipping method"))
  319. return HttpResponseRedirect(reverse('checkout:shipping-method'))
  320. def get_context_data(self, **kwargs):
  321. # Return kwargs directly instead of using 'params' as in django's
  322. # TemplateView
  323. ctx = super(PaymentDetailsView, self).get_context_data(**kwargs)
  324. ctx.update(kwargs)
  325. return ctx
  326. def get_template_names(self):
  327. return [self.template_name_preview] if self.preview else [
  328. self.template_name]
  329. def render_preview(self, request, **kwargs):
  330. """
  331. Show a preview of the order.
  332. If sensitive data was submitted on the payment details page, you will
  333. need to pass it back to the view here so it can be stored in hidden form
  334. inputs. This avoids ever writing the sensitive data to disk.
  335. """
  336. ctx = self.get_context_data()
  337. ctx.update(kwargs)
  338. return self.render_to_response(ctx)
  339. def can_basket_be_submitted(self, basket):
  340. for line in basket.lines.all():
  341. is_permitted, reason = line.product.is_purchase_permitted(self.request.user, line.quantity)
  342. if not is_permitted:
  343. return False, reason, reverse('basket:summary')
  344. return True, None, None
  345. def get_default_billing_address(self):
  346. """
  347. Return default billing address for user
  348. This is useful when the payment details view includes a billing address
  349. form - you can use this helper method to prepopulate the form.
  350. Note, this isn't used in core oscar as there is no billing address form
  351. by default.
  352. """
  353. if not self.request.user.is_authenticated():
  354. return None
  355. try:
  356. return self.request.user.addresses.get(is_default_for_billing=True)
  357. except UserAddress.DoesNotExist:
  358. return None
  359. def submit(self, basket, payment_kwargs=None, order_kwargs=None):
  360. """
  361. Submit a basket for order placement.
  362. The process runs as follows:
  363. * Generate an order number
  364. * Freeze the basket so it cannot be modified any more (important when
  365. redirecting the user to another site for payment as it prevents the
  366. basket being manipulated during the payment process).
  367. * Attempt to take payment for the order
  368. - If payment is successful, place the order
  369. - If a redirect is required (eg PayPal, 3DSecure), redirect
  370. - If payment is unsuccessful, show an appropriate error message
  371. :basket: The basket to submit.
  372. :payment_kwargs: Additional kwargs to pass to the handle_payment method.
  373. :order_kwargs: Additional kwargs to pass to the place_order method.
  374. """
  375. if payment_kwargs is None:
  376. payment_kwargs = {}
  377. if order_kwargs is None:
  378. order_kwargs = {}
  379. # Domain-specific checks on the basket
  380. is_valid, reason, url = self.can_basket_be_submitted(basket)
  381. if not is_valid:
  382. messages.error(self.request, reason)
  383. return HttpResponseRedirect(url)
  384. # We generate the order number first as this will be used
  385. # in payment requests (ie before the order model has been
  386. # created). We also save it in the session for multi-stage
  387. # checkouts (eg where we redirect to a 3rd party site and place
  388. # the order on a different request).
  389. order_number = self.generate_order_number(basket)
  390. self.checkout_session.set_order_number(order_number)
  391. logger.info("Order #%s: beginning submission process for basket #%d", order_number, basket.id)
  392. # Freeze the basket so it cannot be manipulated while the customer is
  393. # completing payment on a 3rd party site. Also, store a reference to
  394. # the basket in the session so that we know which basket to thaw if we
  395. # get an unsuccessful payment response when redirecting to a 3rd party
  396. # site.
  397. self.freeze_basket(basket)
  398. self.checkout_session.set_submitted_basket(basket)
  399. # Handle payment. Any payment problems should be handled by the
  400. # handle_payment method raise an exception, which should be caught
  401. # within handle_POST and the appropriate forms redisplayed.
  402. error_msg = _("A problem occurred while processing payment for this "
  403. "order - no payment has been taken. Please "
  404. "contact customer services if this problem persists")
  405. pre_payment.send_robust(sender=self, view=self)
  406. total_incl_tax, total_excl_tax = self.get_order_totals(basket)
  407. try:
  408. self.handle_payment(order_number, total_incl_tax, **payment_kwargs)
  409. except RedirectRequired, e:
  410. # Redirect required (eg PayPal, 3DS)
  411. logger.info("Order #%s: redirecting to %s", order_number, e.url)
  412. return HttpResponseRedirect(e.url)
  413. except UnableToTakePayment, e:
  414. # Something went wrong with payment but in an anticipated way. Eg
  415. # their bankcard has expired, wrong card number - that kind of
  416. # thing. This type of exception is supposed to set a friendly error
  417. # message that makes sense to the customer.
  418. msg = unicode(e)
  419. logger.warning("Order #%s: unable to take payment (%s) - restoring basket", order_number, msg)
  420. self.restore_frozen_basket()
  421. # We re-render the payment details view
  422. self.preview = False
  423. return self.render_to_response(self.get_context_data(error=msg))
  424. except PaymentError, e:
  425. # A general payment error - Something went wrong which wasn't
  426. # anticipated. Eg, the payment gateway is down (it happens), your
  427. # credentials are wrong - that king of thing.
  428. # It makes sense to configure the checkout logger to
  429. # mail admins on an error as this issue warrants some further
  430. # investigation.
  431. msg = unicode(e)
  432. logger.error("Order #%s: payment error (%s)", order_number, msg)
  433. self.restore_frozen_basket()
  434. self.preview = False
  435. return self.render_to_response(self.get_context_data(error=error_msg))
  436. except Exception, e:
  437. # Unhandled exception - hopefully, you will only ever see this in
  438. # development.
  439. logger.error("Order #%s: unhandled exception while taking payment (%s)", order_number, e)
  440. logger.exception(e)
  441. self.restore_frozen_basket()
  442. self.preview = False
  443. return self.render_to_response(self.get_context_data(error=error_msg))
  444. post_payment.send_robust(sender=self, view=self)
  445. # If all is ok with payment, try and place order
  446. logger.info("Order #%s: payment successful, placing order", order_number)
  447. try:
  448. return self.handle_order_placement(
  449. order_number, basket, total_incl_tax, total_excl_tax,
  450. **order_kwargs)
  451. except UnableToPlaceOrder, e:
  452. # It's possible that something will go wrong while trying to
  453. # actually place an order. Not a good situation to be in as a
  454. # payment transaction may already have taken place, but needs
  455. # to be handled gracefully.
  456. logger.error("Order #%s: unable to place order - %s",
  457. order_number, e)
  458. logger.exception(e)
  459. msg = unicode(e)
  460. self.restore_frozen_basket()
  461. return self.render_to_response(self.get_context_data(error=msg))
  462. def generate_order_number(self, basket):
  463. """
  464. Return a new order number
  465. """
  466. return OrderNumberGenerator().order_number(basket)
  467. def freeze_basket(self, basket):
  468. """
  469. Freeze the basket so it can no longer be modified
  470. """
  471. # We freeze the basket to prevent it being modified once the payment
  472. # process has started. If your payment fails, then the basket will
  473. # need to be "unfrozen". We also store the basket ID in the session
  474. # so the it can be retrieved by multistage checkout processes.
  475. basket.freeze()
  476. def handle_payment(self, order_number, total, **kwargs):
  477. """
  478. Handle any payment processing and record payment sources and events.
  479. This method is designed to be overridden within your project. The
  480. default is to do nothing as payment is domain-specific.
  481. This method is responsible for handling payment and recording the
  482. payment sources (using the add_payment_source method) and payment
  483. events (using add_payment_event) so they can be
  484. linked to the order when it is saved later on.
  485. """
  486. pass
  487. # =========
  488. # Thank you
  489. # =========
  490. class ThankYouView(DetailView):
  491. """
  492. Displays the 'thank you' page which summarises the order just submitted.
  493. """
  494. template_name = 'checkout/thank_you.html'
  495. context_object_name = 'order'
  496. def get_object(self):
  497. # We allow superusers to force an order thankyou page for testing
  498. order = None
  499. if self.request.user.is_superuser:
  500. if 'order_number' in self.request.GET:
  501. order = Order._default_manager.get(number=self.request.GET['order_number'])
  502. elif 'order_id' in self.request.GET:
  503. order = Order._default_manager.get(id=self.request.GET['orderid'])
  504. if not order:
  505. if 'checkout_order_id' in self.request.session:
  506. order = Order._default_manager.get(pk=self.request.session['checkout_order_id'])
  507. else:
  508. raise Http404(_("No order found"))
  509. return order