def checkout_success(request, order_number): """ handle successful checkouts """ save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) # attach the user's profile to the order order.user_profile = profile order.save() # save the users info if save_info: profile_data = { 'default_phone_number': order.phone_number, 'default_country': order.country, 'default_post_code': order.post_code, 'default_town_or_city': order.town_or_city, 'default_street_address1': order.street_address1, 'default_street_address2': order.street_address2, 'default_county': order.county, } user_profile_form = UserProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() messages.success(request, f'Order successfully processed! \ Your order number is {order_number}. A confirmation \ email will be sent to {order.email}.') if 'bag' in request.session: del request.session['bag'] template = 'checkout/checkout_success.html' context = { 'order': order, } return render(request, template, context)
def checkout_success(request, order_number): """ View that will be rendered when the client successfully filled and submitted the form""" save_info = request.session.get('save_info') # Check to see if user selected the save form information option order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) # Attach the user's profile to the order order.user_profile = profile order.save() # Save the user's info if available if save_info: profile_data = { 'default_phone_number': order.phone_number, 'default_country': order.country, 'default_postcode': order.postcode, 'default_town_or_city': order.town_or_city, 'default_street_address1': order.street_address1, 'default_street_address2': order.street_address2, 'default_county': order.county, } user_profile_form = UserProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() messages.success(request, f'Your order has been successfully processed! \ Your order number is {order_number}. A confirmation \ email has been sent to {order.email}.') if 'cart' in request.session: del request.session['cart'] template = 'checkout/checkout_success.html' context = { 'order': order, } return render(request, template, context)
def checkout_success(request, receipt_number): """ Handle successful checkouts """ save_info = request.session.get('save_info') receipt = get_object_or_404(Receipt, receipt_number=receipt_number) if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) # Attach the user's profile to the order receipt.user_profile = profile receipt.save() if save_info: profile_data = { 'default_phone_number': receipt.phone_number, 'default_country': receipt.country, 'default_postcode': receipt.postcode, 'default_town_or_city': receipt.town_or_city, 'default_street_address': receipt.street_address, } user_profile_form = UserProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() messages.success( request, f'Order successfully processed! \ Your receipt number is {receipt_number}. A confirmation \ email will be sent to your email at: {receipt.email}.') if 'basket' in request.session: del request.session['basket'] template = 'checkout/checkout_success.html' context = { 'receipt': receipt, } return render(request, template, context)
def checkout_success(request, order_number): """ Handle successful checkouts """ save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) profile = UserProfile.objects.get(user=request.user) profile.membership = order.membership profile.save() # Attach the users profile to the order order.user_profile = profile order.save() if save_info: profile_data = { 'default_full_name': order.full_name, 'default_email': order.email, 'default_street_address1': order.street_address1, 'default_street_address2': order.street_address2, 'default_town_or_city': order.town_or_city, 'default_postcode': order.postcode, 'default_country': order.country, 'membership': order.membership, } user_profile_form = UserProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() messages.success( request, f'Order successfully processed. \ Your order number is {order_number}. A confirmation \ email has been sent to {order.email}.') if 'basket' in request.session: del request.session['basket'] template = 'checkout/checkout_success.html' context = { 'order': order, } return render(request, template, context)
def checkout_success(request, order_number): """ Handle successful checkouts """ save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) order.user_profile = profile order.save() if save_info: profile_data = { 'default_phone_number': order.phone_number, 'default_country': order.country, 'default_postcode': order.postcode, 'default_town_or_city': order.town_or_city, 'default_street_address': order.street_address, 'default_county': order.county, } user_profile_form = UserProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() messages.success( request, f'Order successfully placed.\ Your order number is {order_number}. A confirmation email \ has been sent to {order.email}') if 'basket' in request.session: del request.session['basket'] template = 'checkout/checkout_success.html' context = { 'order': order, } return render(request, template, context)
def checkout_success(request, order_number): """ A view to handle successfull checkouts """ save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) order.user_profile = profile order.save() if save_info: profile_data = { 'default_full_name': order.full_name, 'default_email': order.email, 'default_phone_number': order.phone_number, 'default_country': order.country, 'default_postcode': order.postcode, 'default_town_or_city': order.town_or_city, 'default_street_address1': order.street_address1, 'default_street_address2': order.street_address2, 'default_county': order.county, } user_profile_form = UserProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() messages.success(request, f'Order: {order_number} \ Your order was successfully processed.') if 'cart' in request.session: del request.session['cart'] template = 'checkout/checkout_success.html' context = { 'order': order, } return render(request, template, context)
def checkout_success(request, order_number): """ Handle successful checkouts """ save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) # Attach the user's profile to the order order.user_profile = profile order.save() # Save the user's info if save_info: profile_data = { 'default_phone': order.phone, 'default_billingCountry': order.billingCountry, 'default_billingPostcode': order.billingPostcode, 'default_billingCity': order.billingCity, 'default_billingAdress1': order.billingAdress1 } user_profile_form = UserProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() messages.success(request, f'Order successfully processed! \ Your order number is {order_number}. A confirmation \ email will be sent to {order.emailAddress}.') request.session.create() template = 'checkout/checkout_success.html' context = { 'order': order, } return render(request, template, context)
def checkout_success(request, order_number): """ Successful checkout handler """ save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) # Attach user profile to order order.user_profile = profile order.save() # Save user contact & delivery details checkbox if save_info: profile_data = { 'default_phone_number': order.phone_number, 'default_street_address': order.street_address, 'default_post_code': order.post_code, 'default_town_or_city': order.town_or_city, 'default_county': order.county, 'default_country': order.country, } user_profile_form = UserProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() messages.success(request, f'Order confirmed! \ Your order number is {order_number}. We have sent \ a confirmation email to {order.email}.') if 'bag' in request.session: del request.session['bag'] template = 'checkout/checkout_success.html' context = { 'order': order, } return render(request, template, context)
def checkout_success(request, order_number): """ Success page for checkouts """ save_info = request.session.get('save-info') order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) order.user_profile = profile order.save() if save_info: profile_data = { 'default_address_line1': order.address_line1, 'default_address_line2': order.address_line2, 'default_city': order.city, 'default_postcode': order.postcode, 'default_country': order.country, 'default_phone_number': order.phone_number, } user_profile_form = UserProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() messages.success(request, f'Order successfully processed \ Your order number is {order_number}. Confirmation \ will be sent to {order.email}.') # remove the users cart items from the session if 'cart' in request.session: del request.session['cart'] template = 'checkout/checkout_success.html' context = { 'order': order } return render(request, template, context)
def complete(request): """ Page sent to on successful subscription creation/payment. Also updates user information if save_shipping variable is true. """ profile = get_object_or_404(UserProfile, user=request.user) save_shipping = request.session["save_shipping"] # Checks the state of save_shipping in the session. # If equals True, updates userprofile delivery address. if save_shipping: shipping_data = request.session["shippingdata"] update_form = UserProfileForm(shipping_data, instance=profile) if update_form.is_valid(): update_form.save() messages.success(request, "Delivery information updated!") # Remove shippingdata for safety reasons, found on # https://docs.djangoproject.com/en/3.2/topics/http/sessions/ del request.session["shippingdata"] template = "subscriptions/complete.html" return render(request, template)
def checkout_success(request, order_number): order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: profile = UserPage.objects.get(user=request.user) order.user_page = profile order.save() user_page_form = UserProfileForm(instance=profile) if user_page_form.is_valid(): user_page_form.save() messages.success( request, f'Yipee! Order accepted!, Your order number is {order_number}') if 'cart' in request.session: del request.session['cart'] template = 'checkout/checkout_success.html' context = { 'order': order, } return render(request, template, context)
def checkout_success(request, order_number): """ Handle successful checkouts """ order = get_object_or_404(Order, order_number=order_number) booking = order.date_booked if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) # Attach the user's profile to the order order.user_profile = profile booking.user_profile = profile order.save() booking.save() profile_data = { 'full_name': order.full_name, 'default_phone_number': order.phone_number, } user_profile_form = UserProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() messages.success( request, f'Order successfully processed! \ Your order number is {order_number}. A confirmation \ email will be sent to {order.email}.') _send_confirmation_email(order, booking) subject = 'A new booking has been made' from_email = '*****@*****.**' message = 'A new booking has been made on The James Master' send_mail(subject, message, from_email, ['*****@*****.**']) template = 'booking/checkout_success.html' context = { 'order': order, } return render(request, template, context)
def checkout_success(request, order_number): """ Handle successful checkouts """ save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) # Attach the user's profile to the order order.user_profile = profile order.save() # Save the user's info if save_info: profile_data = { 'default_phone_number': order.phone_number, 'default_country': order.country, 'default_postcode': order.postcode, 'default_town_or_city': order.town_or_city, 'default_street_address1': order.street_address1, 'default_street_address2': order.street_address2, 'default_county': order.county, } user_profile_form = UserProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() if 'basket' in request.session: del request.session['basket'] template = 'checkout/checkout_success.html' context = { 'order': order, } return render(request, template, context)
def checkout_success(request, order_number): """ Success Checkout Handler """ save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) order.user_profile = profile order.save() if save_info: profile_data = { 'default_phone_number': order.phone_number, 'default_country': order.country, 'default_postcode': order.postcode, 'default_town_or_city': order.town_or_city, 'default_street_address1': order.street_address1, 'default_street_address2': order.street_address2, 'default_county': order.county, } user_profile_form = UserProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() # messages.success(request, f'Order { order_number } Successed!\ # We will send you the confirmation detail to { order.email }.') if 'bag' in request.session: del request.session['bag'] template = 'checkout/checkout_success.html' context = { 'order': order, } return render(request, template, context)
def test_checkout_view_autofill_if_logged_in_with_info_saved(self): # Check if user is authenticated, autofil form session = self.client.session session['bag'] = self.bag_with_item session.save() self.client.force_login(self.testUser) response = self.client.get('/checkout/') user_profile = get_object_or_404(UserProfile, user=self.testUser) user_profile_form = UserProfileForm({ 'default_phone_number': '0851234567', 'default_street_address11': 'here', 'default_street_address2': 'here', 'default_town_or_city': 'herecity', 'default_county': 'herecounty', 'default_postcode': 'herepostcode', 'default_country': 'US' }, instance=user_profile ) self.assertTrue(user_profile_form.is_valid()) user_profile_form.save() order_form = response.context['order_form'] self.assertGreater(len(order_form.initial), 1)
def checkout_success(request, order_number): """ Handle successful checkout """ save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) order.user_profile = profile order.save() if save_info: profile_data = { 'default_full_name': order.full_name, 'default_email': order.email, 'default_phone_number': order.phone_number, } user_profile_form = UserProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() messages.success( request, f'Order successfully proceessed! \ Your order number is {order_number}. A confirmation \ email will be sent to {order.email}.') if 'cart' in request.session: del request.session['cart'] template = 'checkout/checkout_success.html' context = { 'order': order, } return render(request, template, context)
def test_profile_address_form_metaclass(self): form = UserProfileForm() self.assertEqual(form.Meta.exclude, ('user', ))
def test_userprofile_form_no_data(self): form = UserProfileForm(data={}) self.assertFalse(form.is_valid()) self.assertEquals(len(form.errors), 9)
def test_profile_form_user_field_excluded(self): form = UserProfileForm() self.assertEqual(form.Meta.exclude, ('user',))
def success(request, total, pk, order_number): """ this view takes the values from the view charge AFTER the charge is deemed successfull Only when it is successfull will this view start to save the user info entered by the user and a confirmation email will be send with some details from the order. Only after a successfull payment will the amount raised be increased for that specific project """ # getting the amount, user info and order details amount = float(total) save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) # adding the order or (changed) user info to the profile page if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) # Attach the user's profile to the order order.user_profile = profile order.save() if save_info: profile_data = { 'default_phone_number': order.phone_number, 'default_country': order.country, 'default_postcode': order.postcode, 'default_town_or_city': order.town_or_city, 'default_street_address1': order.street_address1, 'default_street_address2': order.street_address2, 'default_county': order.county, } user_profile_form = UserProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() # get the project for which a charge has been made and add the amount to the existing number raised for that project project = get_object_or_404(Project, pk=pk) project.raised += amount project.save(update_fields=["raised"]) project_user = get_object_or_404(User, username=project.user_profile) # send a confirmation email with the order details to the user that made the order new_line = '\n' send_mail( f'Growing Funds: confirmation order {order_number}', f'Dear {order.full_name},{new_line}{new_line}Thank you for pledging ${amount} to project {project.title}{new_line}Hope to see you again soon.{new_line}{new_line}Kind Regards, Growing Funds ', 'GrowingFunds <settings.EMAIL_HOST_USER>', [order.email], fail_silently=False, ) # send an email with the order details to the project host message = f'Dear {project_user},{new_line}{new_line}' \ f'You have a new order for ${amount} for project {project.title}.{new_line}' \ f'The client requested {order.reward} as reward.{new_line}{new_line}'\ f'Delivery Information for this order:{new_line}{new_line}' \ f'Name: {order.full_name}{new_line}' \ f'Address 1: {order.street_address1}{new_line}' \ f'Address 2: {order.street_address2}{new_line}' \ f'postcode: {order.postcode}{new_line}' \ f'Town or city: {order.town_or_city}{new_line}' \ f'County: {order.county}{new_line}' \ f'Country: {order.country.name}{new_line}' \ f'Phonenumber: {order.phone_number}{new_line}' \ f'Email: {order.email}{new_line}{new_line}' \ f'Kind Regards, Growing Funds' \ message_nothing = f'Dear {project_user},{new_line}{new_line}' \ f'You have a new order for ${amount} for project {project.title}.{new_line}' \ f'The client requested {order.reward} as reward.{new_line}{new_line}'\ f'Kind Regards, Growing Funds' \ if order.reward == 'Nothing': send_mail( f'Growing Funds: confirmation order {order_number}', message_nothing, 'GrowingFunds <settings.EMAIL_HOST_USER>', [project_user.email], fail_silently=False, ) else: send_mail( f'Growing Funds: confirmation order {order_number}', message, 'GrowingFunds <settings.EMAIL_HOST_USER>', [project_user.email], fail_silently=False, ) print("email", order.email) context = { 'project': project, 'amount': amount, 'order': order, } return render(request, 'payment_success.html', context)
def checkout_success(request, order_number): """ Handle successful checkouts """ save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) # Attach the user's profile to the order order.user_profile = profile order.save() # Save the user's info if save_info: profile_data = { 'default_phone_number': order.phone_number, 'default_country': order.country, 'default_postcode': order.postcode, 'default_town_or_city': order.town_or_city, 'default_street_address1': order.street_address1, 'default_street_address2': order.street_address2, 'default_county': order.county, } user_profile_form = UserProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() messages.success( request, f'Order successfully processed! \ Your order number is {order_number}. A confirmation \ email will be sent to {order.email}.') # This is where orders are stored for digital downloads. basket = request.session.get('basket', {}) if basket != {}: for item in basket['items']: product = get_object_or_404(Product, pk=item['item_id']) sku = product.sku name = product.friendly_name if item['digital_download']: user = request.user number_of_times_downloaded = 0 ContentReadyToDownload.objects.create( user=user, sku=sku, name=name, product=product, number_of_times_downloaded=number_of_times_downloaded) for link in item['linked_products']: Linked_Product.objects.create(order_id=order, linked_product=link, product=product) emptyingBasket(request) linked_product = Linked_Product.objects.filter(order_id=order.id).exclude( linked_product='Not linked').exclude(linked_product='Not available') template = 'checkout/checkout_success.html' context = {'order': order, 'linked_product': linked_product} return render(request, template, context)
def test_no_fields_are_required(self): form = UserProfileForm({'default_first_name': ''}) self.assertTrue(form.is_valid())
def checkout_success(request, order_number): # Check the session to see if the user wanted to save their info save_info = request.session.get('save_info') order = Order.objects.get(order_number=order_number) no_errors = True # Attach the order to the user's profile # Handle issues w/ appropriate warnings if request.user.is_authenticated: try: user_profile = UserProfile.objects.get(user=request.user) # User the standard UserProfileForm to save to profile if save_info: profile_data = { 'default_phone_number': order.phone_number, 'default_country': order.country, 'default_postcode': order.postcode, 'default_town_or_city': order.town_or_city, 'default_street_address1': order.street_address1, 'default_street_address2': order.street_address2, 'default_county': order.county, } user_profile_form = UserProfileForm(profile_data, instance=user_profile) if user_profile_form.is_valid(): user_profile_form.save() else: no_errors = False messages.warning(request, ( f'Your order was successfully processed, but your information ' f'could not be saved to your profile. Please try adding it ' f'manually on your profile page. Your order number is {order_number}. ' f'A confirmation email will be sent to {order.email}.') ) # Now attempt to attach the order to the user's profile try: order.user_profile = user_profile order.save() except: no_errors = False messages.warning(request, ( f'Your order was successfully processed, but you may not see this ' f'order in your order history in your profile due to an error attaching ' f'the order to your profile. Please contact us for any assistance ' f'needed with this order. Your order number is {order_number}. ' f'A confirmation email will be sent to {order.email}.') ) except UserProfile.DoesNotExist: no_errors = False messages.warning(request, ( f'Your order was successfully processed, but your information ' f'could not be saved to your profile because your profile was ' f'not found. Please contact us if you would like to save your ' f'information for future orders. Your order number is {order_number}. ' f'A confirmation email will be sent to {order.email}.') ) # If there were no issues, provide a standard success message if no_errors: messages.success(request, f'Order successfully processed! Your order number is {order_number}. A confirmation email will be sent to {order.email}.') # Send a confirmation email cust_email = order.email subject = render_to_string('checkout/confirmation_emails/confirmation_email_subject.txt', {'order': order}) body = render_to_string('checkout/confirmation_emails/confirmation_email_body.txt', {'order': order, 'contact_email': settings.DEFAULT_FROM_EMAIL}) send_mail( subject, body, settings.DEFAULT_FROM_EMAIL, [cust_email] ) # Empty the customer's cart del request.session['cart'] template = 'checkout/checkout_success.html' context = { 'order': order } return render(request, template, context)
def checkout_success(request, order_number): """ Handle successful checkouts """ save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) # Attach the user's profile to the order order.user_profile = profile order.save() # Save the user's info if save_info: profile_data = { 'default_phone_number': order.phone_number, 'default_country': order.country, 'default_postcode': order.postcode, 'default_town_or_city': order.town_or_city, 'default_street_address1': order.street_address1, 'default_street_address2': order.street_address2, 'default_county': order.county, } user_profile_form = UserProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() messages.success(request, f'Order successfully processed! \ Your order number is {order_number}. A confirmation \ email will be sent to {order.email}.') recipient_email = order.email, email_body = render_to_string( 'checkout/confirmation_emails/confirmation_email_body.txt', {'order': order, 'contact_email': settings.DEFAULT_FROM_EMAIL} ) meil_subject = render_to_string( 'checkout/confirmation_emails/confirmation_emails_subject.txt', {'order': order} ) try: send_mail( meil_subject, email_body, settings.DEFAULT_FROM_EMAIL, recipient_email, ) except Exception as ex: print(ex) if 'bag' in request.session: del request.session['bag'] template = 'checkout/checkout_success.html' context = { 'order': order, } return render(request, template, context)
def checkout(request): """ view to display checkout page """ stripe_public_key = settings.STRIPE_PUBLIC_KEY stripe_secret_key = settings.STRIPE_SECRET_KEY bag = request.session.get('bag', {}) store_status = get_object_or_404(Store, id=1) if not bag: messages.error(request, "There's nothing in your bag at the moment") return redirect(reverse('products')) if store_status.store_status == "close": messages.error( request, "We are presently closed and cannot accept payments") return redirect(reverse('products')) profile = get_object_or_404(UserProfile, user__username=request.user) if request.method == 'POST': save_info = request.POST.get('save-info') order_form = OrderForm(request.POST) if order_form.is_valid(): order = order_form.save(commit=False) pid = request.POST.get('client_secret').split('_secret')[0] order.stripe_pid = pid order.original_bag = json.dumps(bag) order.user_profile = profile order.save() # Save items to Orderlineitem for item_id, item_data in bag.items(): product = Product.objects.get(id=item_id) if isinstance(item_data, int): order_line_item = OrderLineItem( order=order, product=product, quantity=item_data, ) order_line_item.save() else: for spice_index, quantity in item_data[ 'spice_index'].items(): order_line_item = OrderLineItem( order=order, product=product, quantity=quantity, spice_index=spice_index, ) order_line_item.save() ''' Update profile data if checked by user''' if save_info: profile_data = { 'default_phone_number': order.phone_number, 'default_street_address1': order.street_address, 'town': order.town, 'default_postcode': order.postcode, } user_profile_form = UserProfileForm( profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() return redirect(reverse( 'checkout_success', args=[order.order_number])) else: messages.error(request, 'There was an error with your form. \ Please double check your information.') return redirect(reverse( 'checkout')) else: # Create Stripe intent request current_bag = bag_contents(request) total = current_bag['grand_total'] stripe_total = round(total * 100) stripe.api_key = stripe_secret_key intent = stripe.PaymentIntent.create( amount=stripe_total, currency=settings.STRIPE_CURRENCY, metadata={ 'bag': json.dumps(request.session.get('bag', {})), 'username': request.user, }, ) order_form = OrderForm(initial={ 'full_name': profile.user.first_name + " " + profile.user.last_name, 'email': profile.user.email, 'phone_number': profile.default_phone_number, 'postcode': profile.default_postcode, 'town': profile.town, 'street_address': profile.default_street_address1, }) context = { 'order_form': order_form, 'stripe_public_key': stripe_public_key, 'client_secret': intent.client_secret, } return render(request, 'checkout/checkout.html', context)
def checkout_success(request, order_number): """ Handle successful checkouts """ save_info = request.session.get("save_info") order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) username = profile.user.username # Attach the user's profile to the Order order.user_profile = profile order.save() pid = order.stripe_pid logger.info(f"{username}s profile attached to Order {pid}.") # If a discount code was used, deactivate it if order.discount_code: discount = order.discount_code discount_code_object = get_object_or_404( DiscountCode, discount_code=discount.discount_code ) discount_code_2_user = DiscountCode2User.objects.get( user=profile, discount_code=discount_code_object ) discount_code_2_user.active = False discount_code_2_user.save() # Save the user's info if the box was checked if save_info is True: profile_data = { # These dict keys match the fields on the user profile model "default_phone_number": order.phone_number, "default_street_address1": order.street_address1, "default_street_address2": order.street_address2, "default_town_or_city": order.town_or_city, "default_county": order.county, "default_country": order.country, "default_postcode": order.postcode, } # Create an instance of the User Profile Form using the data # and update the Profile we obtained above user_profile_form = UserProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() logger.info(f"{username}s default profile info has been updated") messages.success( request, f"Order successfully processed! \ Your order number is {order_number}. A confirmation \ email will be sent to {order.email}.", ) # Empty the Shopping Cart if "cart" in request.session: del request.session["cart"] # Remove the used Discount Code from the Session if "discount" in request.session: del request.session["discount"] template = "checkout/checkout_success.html" context = { # Send the order back to the template "order": order, } return render(request, template, context)
def handle_payment_intent_succeeded(self, event): """ Handles the payment_intent.succeeded webhook from Stripe """ intent = event.data.object pid = intent.id stripe.api_key = settings.STRIPE_SECRET_KEY booking_number = intent.metadata.booking_number save_info = intent.metadata.save_info username = intent.metadata.username profile = None billing_details = intent.charges.data[0].billing_details shipping_details = intent.shipping total = round(intent.charges.data[0].amount / 100, 2) """ Sets any shipping details in the payment intent with a value of an empty string to None """ for field, value in shipping_details.address.items(): if value == "": shipping_details.address[field] = None # Attempts to retrieve the booking every second for five seconds. booking_exists = False attempt = 1 while attempt <= 5: try: booking = Booking.objects.get( booking_number=booking_number, full_name__iexact=shipping_details.name, email__iexact=billing_details.email, phone_number__iexact=shipping_details.phone, country__iexact=shipping_details.address.country, postcode__iexact=shipping_details.address.postal_code, town_or_city__iexact=shipping_details.address.city, street_address1__iexact=shipping_details.address.line1, street_address2__iexact=shipping_details.address.line2, county__iexact=shipping_details.address.state, grand_total=total, paid=True, stripe_pid=pid, ) booking_exists = True break except Booking.DoesNotExist: attempt += 1 time.sleep(1) """ Sends the confirmation email and a success response to stripe if the booking already exists """ if booking_exists: self.send_confirmation_email(booking) return HttpResponse(content=f'Webhook received: {event["type"]} | \ SUCCESS: Verified booking already in database', status=200) else: booking = None try: """ If booking_exists remains false after 5 attempts, try and retreive the booking, save the checkout form and update the payment details in the booking """ booking = Booking.objects.get(booking_number=booking_number) form_data = { 'full_name': shipping_details.name, 'email': billing_details.email, 'phone_number': shipping_details.phone, 'street_address1': shipping_details.address.line1, 'street_address2': shipping_details.address.line2, 'town_or_city': shipping_details.address.city, 'county': shipping_details.address.state, 'country': shipping_details.address.country, 'postcode': shipping_details.address.postal_code, } booking_form = CheckoutForm(form_data, instance=booking) if booking_form.is_valid(): booking = booking_form.save(commit=False) booking.paid = True booking.stripe_pid = pid booking.save() """ Saves the user's details to their profile if they were signed in and they checked the save_info checkbox in the form """ if username != 'AnonymousUser': profile = UserProfile.objects.get(user__username=username) booking.user_profile = profile booking.save() if save_info: profile_data = { 'phone_number': booking.phone_number, 'street_address1': booking.street_address1, 'street_address2': booking.street_address2, 'town_or_city': booking.town_or_city, 'county': booking.county, 'country': booking.country, 'postcode': booking.postcode, } user_profile_form = UserProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() # Sends an error response to stripe if the booking does not exist except Booking.DoesNotExist: return HttpResponse( content=f'Webhook received: {event["type"]} | \ ERROR: Booking does not exist', status=500) """ Sends the confirmation email and a success response to stripe if the booking already exists """ self.send_confirmation_email(booking) return HttpResponse(content=f'Webhook received: {event["type"]} | \ SUCCESS: Created booking in webhook', status=200)
def register(request): # Like before, get the request's context. context = RequestContext(request) # A boolean value for telling the template whether the registration was successful. # Set to False initially. Code changes value to True when registration succeeds. registered = False # If it's a HTTP POST, we're interested in processing form data. if request.method == 'POST': # Attempt to grab information from the raw form information. # Note that we make use of both UserForm and UserProfileForm. user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) # If the two forms are valid... if user_form.is_valid() and profile_form.is_valid(): # Save the user's form data to the database. user = user_form.save() # Now we hash the password with the set_password method. # Once hashed, we can update the user object. user.set_password(user.password) user.save() # Now sort out the UserProfile instance. # Since we need to set the user attribute ourselves, we set commit=False. # This delays saving the model until we're ready to avoid integrity problems. profile = profile_form.save(commit=False) profile.user = user # Did the user provide a profile picture? # If so, we need to get it from the input form and put it in the UserProfile model. if 'picture' in request.FILES: profile.picture = request.FILES['picture'] # Now we save the UserProfile model instance. profile.save() # Update our variable to tell the template registration was successful. registered = True return redirect('home') else: # Invalid form or forms - mistakes or something else? # Print problems to the terminal. # They'll also be shown to the user. print user_form.errors, profile_form.errors # Not a HTTP POST, so we render our form using two ModelForm instances. # These forms will be blank, ready for user input. else: user_form = UserForm() profile_form = UserProfileForm() # Render the template depending on the context. return render_to_response( 'accounts/register.html', { 'user_form': user_form, 'profile_form': profile_form, 'registered': registered }, context)
def create_order(request): if request.method == 'POST': service_id = request.POST['service_id'] profile = UserProfile.objects.get(user=request.user) orders = Order.objects.filter(service_id=service_id, user_profile=profile, status="paid") if orders.count() > 0: return JsonResponse( { 'msg': 'you have already ordered this service, check your order history or available ' 'quizzes.' }, status=400) form_data = { 'full_name': request.POST['full_name'], 'email': request.POST['email'], 'phone_number': request.POST['phone_number'], 'country': request.POST['country'], 'postcode': request.POST['postcode'], 'town_or_city': request.POST['town_or_city'], 'street_address1': request.POST['street_address1'], 'street_address2': request.POST['street_address2'], 'county': request.POST['county'], } order_form = OrderForm(form_data) if order_form.is_valid(): order = order_form.save(commit=False) pid = request.POST.get('client_secret').split('_secret')[0] order.stripe_pid = pid service_id = Service.objects.get(id=service_id) order.service_id = service_id profile = UserProfile.objects.get(user=request.user) # Attach the user's profile and total amount to the order order.user_profile = profile order.total_amount = settings.PRICE order.save() save_info = request.POST['save-info'] if save_info: profile_data = { 'main_full_name': order.full_name, 'main_phone_number': order.phone_number, 'main_country': order.country, 'main_postcode': order.postcode, 'main_town_or_city': order.town_or_city, 'main_street_address1': order.street_address1, 'main_street_address2': order.street_address2, 'main_county': order.county, } user_profile_form = UserProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() return JsonResponse({'order_id': order.order_number}, status=200) else: return JsonResponse( { 'msg': 'There was an error with your form. \ Please double check your information.' }, status=400)
def test_profile_fields_in_meta(self): """ check if correct fields are in Metaclass """ form = UserProfileForm() self.assertEqual(form.Meta.exclude, ("user",))