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 27KB

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