Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
87 views

Python Ecommerce

This document provides an overview of building an e-commerce website using Django. It will cover creating templates, views, URLs, adding static files, and configuring the main template. It also discusses building out the store and cart pages by adding products, cart functionality, and styling elements.

Uploaded by

Mukesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views

Python Ecommerce

This document provides an overview of building an e-commerce website using Django. It will cover creating templates, views, URLs, adding static files, and configuring the main template. It also discusses building out the store and cart pages by adding products, cart functionality, and styling elements.

Uploaded by

Mukesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Hey, welcome to this Django e-commerce series!

In this series, we'll be building a complete


e-commerce website with payment integration. Users will have the option to shop either as
a guest or as a registered user. This means they can add items to their cart, check out, and
complete purchases without creating an account. On the other hand, users can also register,
create an account, and shop as a registered user. We'll cover both aspects of this
functionality.

Let's dive into the website. In the pre-release, we showcased a simple store where users can
add items to the cart, update quantities, and proceed to checkout. For logged-in users, the
core functionality includes adding shipping information, completing the purchase, and being
redirected back to the home page.

If we log out, the cart is emptied. However, we're now going to build a cart in a different
way. Instead of adding items to the database, we'll construct the cart in the browser. This
allows users to update their cart and see the changes instantly. The cart will be stored in
cookies, ensuring persistence even if the user logs out and returns later.

Now, let's discuss the technologies used in building this website. To keep it beginner-
friendly, we won't use front-end frameworks or REST APIs extensively. JavaScript will be
employed for the front-end, specifically for the Add to Cart functionality and handling site
cookies. The primary technology stack is Django, with no additional libraries. The focus is on
the core functionality, including data structure, cart management, payment integration, and
guest user checkout.

While the series remains relatively simple, there might be some bonus features. For those
wanting a more advanced approach, I might create a replica with a REST API or a React
Django e-commerce website in the future. Keep an eye out for that!

To get started, you can download the source code from the provided link in the video
description or visit the CodeWithSteps website. The series will be divided into modules,
each covered in its own video. The project overview is available for reference. I've set up the
project, created the first app, and configured it within our project.

If you're new to Django and just want to get started, follow these steps. First, install Django
and set up your app using the command django-admin startproject. In this case, we named
our app "ecommerce" and dove into it. After that, we created a new app called "store"
within our Django project. The app was configured within the installed apps list.
Now, moving on to part two in module one, we'll start by creating our templates. If you
prefer to skip this and focus on the database part, you can start with module number two.
However, the video for that module is free. In the store app, create a folder called
"templates" and another folder within it named "store."

Now, let's create three templates: main.html, store.html, cart.html, and checkout.html. Add
an <h3> tag to each template for verification. The goal is to ensure that the templates are
configured correctly.

In part three, where we discuss views and URLs, follow the steps outlined in the video.
Create three views in your views.py file: store, cart, and checkout. These will be function-
based views rendering the corresponding templates.

In step two, configure the URLs in your urls.py file. Import the necessary modules, create a
list of URL patterns, and assign the views to the appropriate paths (store, cart, checkout).

Lastly, in your project's urls.py file, include the app's URLs using the include function.

Now, run the server using python manage.py runserver and check if it's running on port
8000. Open your browser and navigate to http://localhost:8000 to ensure that all three
pages (store, cart, and checkout) are being rendered correctly.

Great! It seems our store is rendering properly, and we've tested the cart and checkout
pages as well. All the pages are working as expected. Now, let's move on to configuring our
static files, which is actually part four, not part three.

Firstly, let's create a folder called "static" within our project's root directory. Inside the
"static" folder, we'll create subfolders for "CSS" and "images." Within "CSS," we'll add a file
named "main.css," which will host our main stylesheet.

Now, let's configure our static files in the project. Open the "settings.py" file and set the
"STATICFILES_DIRS" variable. This ensures that Django knows where to find our static files.

Next, we'll link our main.css file to our templates. In our "main.html" template, load the
static files using the {% load static %} template tag. Then, include the main.css file in the
template using the appropriate link.
With static files set up, we can verify that our styling is working by adding a simple
background color to the body in our main.css file.

Now, let's add an image to our static files to ensure everything is configured correctly.
Download an image (e.g., a cart icon) and save it in the "images" folder within the "static"
directory.

In the main.html file, use the {% load static %} tag and add an image tag to display the
downloaded image.

With styling and images confirmed, we can proceed to create our main template in part five.
Open the "main.html" file within the "templates/store/" directory. Start with the HTML
boilerplate and include necessary tags for static files, such as the {% load static %} tag.

In step two, add the <meta name="viewport" content="width=device-width, initial-


scale=1.0"> tag to ensure responsiveness on different devices.

In step three, include Bootstrap in the template by copying the relevant CSS and JavaScript
links. Place the Bootstrap CSS link above our custom stylesheet and the Bootstrap JavaScript
link at the bottom, just above the closing body tag.

Now, let's create a placeholder for our navbar. Add a container with the class "container"
and a block content within it. This will serve as the container for our pages. We've also
included a basic navbar with a title and horizontal rule for separation.

In step five, extend the main.html template in other templates like cart.html and
checkout.html using the {% extends "store/main.html" %} tag. This ensures consistency
across all pages.

Now, we can customize our navbar. In step three, replace the existing navbar with the
Bootstrap navbar code provided. Adjust the theme to dark, change titles and URLs, and
remove unnecessary links. Also, customize the right side to display a cart icon, linking to the
cart page.
For styling issues with the cart icon, use the provided CSS code to set the width, display
properties, and margin.

Finally, check if the changes are reflected on the pages and ensure that the navbar appears
correctly with the desired styling and functionality.

Welcome to our Django e-commerce series! Throughout this series, we'll be building a
complete e-commerce website with payment integration, allowing users to shop as guests
or registered users. The cart functionality will be constructed in the browser using cookies
for persistence even after logging out.

Technologically, we'll keep it beginner-friendly using Django without additional libraries.


JavaScript will handle front-end functionalities such as Add to Cart and cookie management.
We'll cover core features like data structure, cart management, payment integration, and
guest user checkout.

While keeping it simple, there might be bonus features. For those seeking a more advanced
approach, a future series might explore REST API or a React Django e-commerce website.

To begin, download the source code from the provided link or CodeWithSteps website. I've
set up the project, created the first app named "ecommerce," and configured it. If you're
new to Django, install it, create a project, and then an app.

In module one, part two, we'll create templates. If you prefer, skip to part two for the
database aspect. In the "store" app, create "templates/store" and add main.html,
store.html, cart.html, and checkout.html with an <h3> tag for verification.

In part three, create three function-based views (store, cart, checkout) in views.py.
Configure URLs in urls.py. In your project's urls.py, include the app's URLs using the include
function.

For static files in part four, create a "static" folder in the project's root, add "CSS" and
"images" subfolders. Configure static files in settings.py. Link main.css in main.html, and
verify styling.
Part five focuses on the main template. Set up HTML boilerplate, include necessary tags, add
viewport meta tag for responsiveness, and integrate Bootstrap for styling. Customize the
navbar for consistency across pages.

In part six, we configure navbar styling using custom CSS. The website should now reflect
the changes.

In part seven, we start building the store page. Create a row with three columns using
Bootstrap classes. Add placeholder images and product titles within box elements. Style the
Add to Cart buttons.

Now, in part eight, we move to the cart page. Download necessary images (arrow-up and
arrow-down) and save in the "images" folder. Create a row with two box elements for the
header and cart items. Build the header with continue shopping link, back arrow button,
item count, total, and checkout link.

In part eight, step three, build cart rows using flex layout. Create a cart-row class for styling.
Each row will have columns for product details, quantity, price, and total. Customize styling
as needed.
Now, your website should display the store and cart pages as expected.

You're configuring the layout using flex containers and adjusting the properties for various
sections like user information, shipping details, payment options, and order summary on a
checkout page. The HTML structure involves divs with specific IDs for different sections like
user-info, shipping-info, and payment-info. Form fields are being manually styled within
these sections for a customized appearance.

A 'Continue' button is implemented for form submission, and payment options are initially
set to be hidden using the 'hidden' class. Upon form submission, the class is modified to
reveal the payment options, including a PayPal section. The design aims at simplicity and
user-friendly interaction.

The right column displays an 'Order Summary' with a back button redirecting users to the
cart page. Cart rows are dynamically created to showcase product images, IDs, quantities,
and totals. The plan is to populate this section dynamically with actual product data from a
database.
In the upcoming video, the focus is on integrating data structures, implementing models,
and rendering real product information on the checkout page. This approach avoids
excessive copying and pasting, ensuring a smoother and more efficient development
process.

Hey everyone, welcome to the second video in this series. In this tutorial, we'll be focusing
on creating our database models and rendering actual items in our templates. Currently, we
have placeholder data, and our goal is to output real items for our products. We'll also
create a real order and populate our cart with actual items, showcasing dynamic data for a
real user.

For those who may not have built the template with me in the last video, you can find all the
code we worked on in the project overview. I'll continue breaking the code into sections,
making it accessible at the end of each video. Module two will be a premium feature,
available for purchase to use as a step-by-step guide. You can unlock all modules for $12.49,
using PayPal, credit card, or a debit card.

Now, let's jump into the coding. In our apps/models.py file, the first step is to import the
default Django user model. We'll then proceed to build our customer model, products,
orders, and more. If you're following along, make sure to check the correct syntax for your
import: from django.contrib.auth.models import User.

In step two, we'll start building our customer model. It will have attributes such as user (a
one-to-one relationship with the default user model), name, and email. We'll also include
the necessary settings, like null=True and blank=True, to handle potential changes later.
Additionally, we set the on_delete attribute to models.CASCADE to ensure data consistency.

Moving on to step three, we'll create our product model, defining attributes like name,
price, and a boolean field for digital products. We'll also set a default value for the boolean
field and configure the null and blank parameters. At this point, we'll leave out the image
field for later customization.

Next up in step four, we'll create the order, order item, and shipping models. The order
model will have a many-to-one relationship with the customer, a date_ordered field, a
complete boolean field, and a transaction_id field. For the order item model, we'll use a
foreign key to connect it to both the order and product models, including attributes for
quantity and date added. The shipping model will be linked to the customer and order
models, with additional fields for address, city, state, zip code, and date added.
After defining our models, we proceed to migrate the database using python manage.py
makemigrations and python manage.py migrate.

In the admin.py file, we register our models with the admin site to make them visible in the
Django admin panel.

The next major step involves adding an image field to the product model. We use the Pillow
library for image processing and configure the media root and URL in the settings to handle
image uploads. Additionally, we update the URLs and include the necessary imports to serve
media files during development.

Now, in the store.html template, we loop through the product queryset and display product
names and prices. We also dynamically render product images using the image URL.

To handle potential errors when an image is missing, we create a model method called
image_url in the models.py file. This method attempts to retrieve the image URL and
returns an empty string if it encounters an exception.

Finally, in the cart.html template, we prepare to render data dynamically. We check if the
user is authenticated and start building the logic to display real data.

That wraps up the steps we've taken in this video. In the next part, we'll continue with user
authentication and further customization of the cart functionality.

In this step, we'll set two conditions: one for an authenticated user and another for a user
not logged in. Let's first check for an authenticated user. If request.user is authenticated,
we'll set the customer value to request.user.customer. This allows us to access the one-to-
one relationship connecting the user and the customer in models.py.

Next, we'll work on obtaining the customer's order. We use the order variable and query it
using order.objects.get_or_create. This method tries to query an object with specific values;
if it doesn't exist, it creates it. We look for an order associated with the customer and having
a completed status of false (an open cart). The result is stored in the order variable.
Now, we need to get the items attached to that order. We use items =
order.orderitem_set.all() to retrieve all order items associated with the current order.

For the scenario where the user is not authenticated, we set the items to an empty list. This
is crucial for preventing issues when looping through the items list in the template.

Moving on to rendering the items in the cart, we focus on replacing the static values such as
image, product name, price, and quantity in the cart.html template. A loop is created for
each item, fetching and displaying the relevant information.

To enhance the dynamic nature of the totals, we create methods in the OrderItem model.
The get_total method calculates the total price of an order item based on the product's
price and the quantity. For the Order model, we add two methods: get_cart_total and
get_cart_items. These methods calculate the total value of the cart and the total quantity of
items in the cart, respectively.

In the cart.html template, we use these methods to display the dynamic totals. Special
attention is given to handling cases where the user is not authenticated. In such instances, a
manual order object is created with placeholder values to ensure the template receives
valid data.

The dynamic cart information is then extended to the checkout page. We copy the logic
from the cart view to the checkout view, passing in the order and items data to the
checkout.html template. The template is updated to reflect the dynamic cart totals and cart
item details.

With these enhancements, users can view and interact with a dynamically updated
shopping cart, providing a foundation for further functionalities in the upcoming modules.

Okay guys, welcome to video number three of this series. In this video, we'll be working on
the Add to Cart functionality, updating the cart, and handling the checkout page. We'll add
JavaScript to our website to handle button clicks, update quantities, remove items, and
more.
We'll start by creating a cart.js file, add event handlers to buttons, and console out some
data. Then, we'll work on the checkout page, adding logic and forms based on the user's
login status and cart items. Payment handling will be addressed in a later module.

Here are the steps we'll go through in this session:


Create the cart.js file and add basic console output.
Add the cart.js file to the main template.
Set up event handlers for buttons with the class "update cart" and add custom attributes for
product ID and action.
Create a view called "update item" to handle the AJAX request for updating the cart.
Add a URL path for the "update item" view.
Set the user in the main template and handle user authentication in the cart.js file.
Create the "update item" view in views.py, returning a JSON response for now.
Add the CSRF token to the headers in the cart.js file to resolve a common issue with sending
POST requests.
Implement the logic in the "update item" view to process the data received from the
frontend.
Let's dive into these steps and enhance the functionality of our e-commerce website.

In the preceding code segment, an adjustment was made outside the action string, and
now, let's proceed to test it. Opening the command prompt, we'll add a few items, ensuring
everything functions correctly. Upon clicking "add," the product ID and action should be
displayed. Great, we have the product ID. Now, let's complete the logic and actually add
items.

Moving forward, we need to query the customer and initiate the order creation process.
Directly below the action and product ID, we retrieve the customer using
request.user.customer. Subsequently, we obtain the product by setting it equal to the
provided product ID. This step is necessary as we pass the product ID as an argument to
product.objects.get. Now that we have the product, the next step is to get or create the
order.

Copying and pasting the previously created logic for obtaining an order attached to the
customer with the value of 'complete' set to false, we now have the order as the return
value. Moving on to creating an order item, we use get_or_create once again. The return
value is assigned to order_item, obtained by calling order_item.objects.get_or_create. We
set the order value to the previously queried order and the product accordingly.

The rationale behind using get_or_create is to handle cases where the order item already
exists. If the order item exists for the given product and order, we don't create a new one;
instead, we modify the quantity. If the action is 'add,' we increment the quantity; if
'remove,' we decrement it.

Proceeding with the conditional statements, if the action is 'add,' we increase the quantity
by setting order_item.quantity to its current value plus one. For 'remove,' we decrease the
quantity. After saving the order item, we check if the quantity is zero or below. If so, we
remove the item using order_item.delete().

This logic is implemented within the page, and data is sent to this view only when a user is
logged in. For guest users clicking these buttons, the action changes accordingly. Testing this
now, we may not see immediate results on the page, but checking the cart will reveal the
updates.

The next step involves refining the code and making it more efficient. Currently, we
manually pass user data into each view to display the cart total. A future enhancement may
involve creating a REST API or using more JavaScript to streamline this process. For now,
we've established a functional system, and in subsequent sections, we'll work on further
improvements.

Continuing from the previous code adjustments, the next task involves adding a shipping
method to the order model. In the order model, a shipping method is introduced to iterate
through all order items. If any product in the order has the 'digital' attribute set to false
(indicating it's a physical item), the shipping method is set to true, indicating the need for
shipping. Subsequently, logic is added to the page to dynamically change this value. If the
shipping field is rendered in the template, it can be accessed as order.shipping or
order['shipping'] for both logged-in and guest users.

To implement this in the models.py file, the order model is updated by adding a shipping
attribute using the property decorator. The default value is set to false, and a loop through
order items checks if any product has 'digital' set to false, updating the shipping attribute
accordingly.
The next step involves rendering the shipping status in the template. The order object,
containing the shipping method, is already passed to the views, so it is accessible in the
template. This is done for all views, including those for guest users, ensuring the value is set
manually.

Now, in the checkout.html page, JavaScript is added to check the shipping status and
conditionally hide the shipping info field. If shipping is false, the inner HTML of the
corresponding wrapper is set to an empty string, effectively hiding the form field.

In the next section, attention is directed to the payment options. A JavaScript event handler
is added to the form submission, preventing the default behavior and hiding the form
button while displaying the payment information wrapper. The button is hidden by adding
the 'hidden' class, and the 'hidden' class is removed from the payment info wrapper,
allowing the payment options to become visible.

This JavaScript is incorporated directly into the checkout.html template to provide specific
functionality for this page. Upon testing, it ensures the seamless hiding and display of form
elements based on shipping requirements and form submission. The integration of these
features enhances the user experience during the checkout process.

is open so that's what that just did we removed one class we added another so let's go to
the next step here and what we want to do is throw in just a default button for now that will
trigger a payment so right now we're gonna let a user check out without actually paying that
will be added in another module but we're gonna throw in a button here that has the idea
of make payment and the text of make payment so we'll close all these out right now and
this is what the buttons gonna look like so once the user adds in this information they can
click make payment and it'll actually process the or so let's close out the picture here and
add that in so go up to our payment wrapper and underneath PayPal option will create a
button and the ID of the button will be make - payment and we'll just say make payment
here so once we have that button there it'll appear once the form data is filled out so let's
just test that we'll add in some data submit it make payment is here what we want to do
next is add in an event handler that will actually send the data so right now what we're
gonna do is first create this function called submit form data and then we're gonna trigger it
and for now all we're gonna do is just console out data is submitted so right now here's our
submit form data function payment button clicked that'll trigger and then in the next part
we'll actually go through that checkout process so back in our checkout HTML page at the
bottom here let's create that function so first thing we'll do is just underneath this an event
handler create the function called submit form data so D and F are capitalized there we're
not passing any parameters for now and let's console dot log payment button clicked so we
have the function and we want to trigger that just after we add the event handler to our
payment button so document dot get element by ID and we're gonna get that new button
so that button was called make dash payment and let's add the event handler so on click so
add event listener and that's gonna be on click here we're gonna trigger that function that
we just created so on click we're gonna put that within a function and we're gonna pass in
the event here we do want to access that later and we're gonna say submit form data so
there we go so we added the event handler to that make payment button we set that click
and we're going to trigger this function so let's test it really quick one more time open up
our console so we can see it so if i refresh it we'll add in some data here so we'll throw that
in click that and then when we submit it payment button click so I think it's just showing up
funny because it was small there but now the function is triggering and we want to in the
next step actually add in the logic for the rest of our form and that submit form data
function so for part four we want to do something similar in step one that we did in the last
step which is hide this name and email field for users that are logged in so if a user is logged
in there's no need to get this information we already know it and if they are then we can
show it so what we're gonna do is write in some logic that's gonna change that and then
we're gonna change up how we see that shipping information or the entire form so if we
don't need to ship the item or the user name does not need to be there we can hide the
entire form and automatically render out the payment button so let's go ahead and take
care of that it looks like I didn't provide a screenshot in here but I wrote out a couple of
scenarios here and I am just gonna copy and paste the logic and then I'll go over it just
because I don't have that image so I think I can just do this slowly and explain as I go so this
logic is gonna be added just underneath this if statement so under the shipping statement
we're gonna paste in to more conditionals so let's just go over these I'll fix the indentation
here and I'll also zoom in to make sure everyone can see this so what we're doing here is
first we're checking if the user is not an anonymous user so if the user is logged in we're
gonna take this user info wrapper so it's kind of like shipping info and it's the one we
created right here and we're gonna say that if the user is not enough an anonymous user so
if they're logged in go ahead and hide that wrapper now if the user shipping information is
false so if the user does not need an item shipped and the user is also logged in go ahead
and hide the entire form wrapper and hide the or open up the payment wrapper so go
ahead and remove the payment wrapper information so the source code will be provided
with all of this so if you need to look this over go ahead and do that but the logic is pretty
simple we're just trying to create some different scenarios here and now as a logged in user
the first thing that we should see is this user form be hidden now we're only seeing the
shipping information so we're logged in we only see that and if we remove an item here that
needs to be shipped so we only have a digital item go to our checkout page now we're
seeing this payment option appear immediately and that entire form is open so I'll quickly
show you what an unauthenticated users gonna look like so we'll log out really quick we'll
go back to the checkout page we don't have any products so that's not gonna show anything
but if we go to the cart go to checkout here now that the user is not authenticated we can
see the user form we don't have any products so shipping is by default set to false so that's
what that takes care of and we can move on to the next step so in the next step what we
want to do is set the total value so we actually want to get this data and send it to the
backend along with some user information so we actually want to get that name email total
shipping information send it to the backend and then eventually in part five will handle
processing the order and that will be the end of this video and module so back to our
checkout page let's set just under shipping let's get the total so we're gonna set of our total
and this is going to be equal to the order total that we passed in through our view and we're
going to set that to a string and the value is going to be order get underscore car underscore
total and we're gonna set the float format so float format and we want two decimal places
to the right so we'll throw in two right there and that needs to be format so we have the
total now and what we want to do is within this submit form day function we want to create
two objects and then pass in some data with those so we're gonna set VAR user form data
and this is going to equal to an object here and we're gonna say name this by default is
gonna be set to null then we want to throw in an email this is also gonna be set to no and
we'll update all these values once the form is actually submitted so these will be updated in
a second here so both will be set to no and we want to pass in the total with the user so
each time this is submitted we always want to throw in that total there and finally we want
to do the same for shipping address so well let's copy this right here and paste it below and
we just need to change these values to our shipping field so for this we're gonna set this to
address and they're supposed to be an exact replica of our form field so in our form field we
have we've manually created each field so they all have a name so we're just getting these
values right here so we have address then we'll bring on city state and zip code so we'll just
copy and paste that and then repeat it let's get rid of total and change this to state and
zipcode so let's also change the value of this to shipping info and that's gonna be a capital I
so we have shipping info user form data and once the form is submitted we want to update
these values so there's probably a way we can do this where we can just set the values
directly in here but because I already wrote up my instructions this way and I just want to
stick with that we're gonna follow along exactly how I set it up there so right now what I do
in my instructions is create this conditional where we check the value of shipping and
anonymous user and update the values depending on what they are so we're first going to
check if shipping is not false so I'll write that conditional here and we're gonna say shipping
and in JavaScript we can do not equals to this way and remember false or that shipping
value is a string value so it's either false or true and in a string value so if shipping is not
equal to false which is what we set up here then we want to update the shipping info object
so I'll paste that in and we're gonna say dot address and we're gonna set the value of
address to the values within the form field so we have the form right here so that means we
can access it this way so we can say form dot address and remember we have all those form
fields in there so we need to get the field and then the value of the field and I want to
repeat this three more times here so we'll set that up and we're just gonna change these
values so shipping city here and state and zipcode so we'll set the zip code and next we
want to do the userform data so we're gonna copy this again right here and take in user
form data so for the if statement first we want to check if this is an anonymous user so if
this user is registered then we don't need to update this because we already have the
information so we're gonna say if user and remember user was set in main dot HTML so
that's how we're able to access that object so if the user is equal to anonymous user and
that's a capital u right there so capital a capital u then let's go ahead and change these
values for a user form data so I'll paste in these two we'll remove the bottom two here and
we want to change the name and the email so we'll set user now form data a name we'll set
that to form dot name value and set the email so we're able to access these from the same
variable because form here is all one big form that we set up with just two different sections
for our fields so we're accessing the same form and setting the values so for the last part in
our modules here in part five we're gonna finish processing disorder so what we're going to
do first is create a view and URL pattern that's going to process this we're gonna send some
data to that view and then in step three through six we're actually going to send that data
and then actually create process this order set the value to complete and take care of
everything like that so let's go ahead and handle that we'll go to step one and in step one
we're gonna call that function process order here it's just going to return the JSON response
here and say payment was submitted and that's URL pattern so we're gonna move checkout
HTML to the right here and I'm gonna close out the model and it will open up the views
we're gonna create the view just underneath our update item view so just under here let's
create the function and we'll call it process order we'll capitalize the oh there throw in a
request and I'm actually just gonna copy and paste this return value so we'll set the JSON
response and for this we'll just say payment complete so we're gonna send back the string
and now let's set the URL pattern so we'll open up URLs py and repeat this process I want to
drag this to the right so we can see it and we're gonna take in or paste it in here and then
pass in process order so this will be process underscore order and I'm going to change the
value here so let's make sure that the view works first so open up our website and paste in
process order or just type it out process underscore order so there we go we have our JSON
response we'll go back to our checkout page and let's go ahead and finish up everything in
checkout dot HTML so now what we need to do is send some post data looks like I messed
something up in our check out HTML page and I think that was when we set up this float
format and that was supposed to be a colon so I hope you noticed that and fixed it but I
wasn't too far back there so we shouldn't have an issue so now that that's fixed let's go back
to our steps and in our steps right here in step two we need to send some post data so
we're gonna set the URL and we're gonna send the post request we're gonna send in our
CSRF token and we're gonna send in those objects for that use form data and shipping info
and then we're gonna refresh the page and send the user to our store so whenever the
store is complete we're gonna redirect them so we'll finish that up let's go ahead and take
care of it I'm gonna close out our URLs dot py file and we'll add in that fetch request inside
of our submit form data function just underneath this if statement so first we'll set the
variable for the URL and that's gonna be the URL that we just says so that's gonna be
processed so forward slash process underscore order so this is where we want to send this
data to and we can create that fetch call so fetch we'll pass in the URL and then we want to
set the method and the headers so method will be a post and for the headers we're gonna
pass in the content type and the CSRF token so that'll be another object right here and we
can do content - type and this will be application for slash JSON so we have the content type
and now we need to do the CSRF token so X - CSRF capital T and then finish out token and
then we can get the CSRF token again because it's in our headers of our main dot HTML file
so CSR F token and we can pass that in and we need to throw in our there and finally we'll
throw in the body so for the body let's set the stringify value first so json stringify and into
stringify we need to pass in our and user information so let's set the value of form and for
form we're gonna pass in the general user information so we'll take in this object here that's
going to give us a name email and the total price and then for shipping so we'll set that
value we're gonna get the shipping info object so we're going to string apply this data we're
gonna send it to the backend and then once that data gets sent we want to in response so
we want to return that promise and then return this payment complete string here so we
want to make sure that's done and then once that's complete we want to send the user
back to our home page so what I'm gonna do here is go to this code block and we're first
gonna grab this response right here and we'll paste that in just after our fetch call so if you
don't have that step-by-step guide go ahead and just type that out it's dot then we have an
arrow function we turn that JSON response there and then we have another promise so
we're gonna paste this in just after dot then and then we're gonna take that data we're
gonna console it out and we're gonna create an alert that's gonna say the transaction was
completed once the once that alert is closed we're gonna send the user back to the home
page and let's quickly print out some data here just so we can see it and we want to know
that the data was sent to process order so we're just gonna say data and we're gonna print
out request body and we want to send that data and be redirected so let's test it so back to
our website let's make sure we're logged in and we'll go to checkout here and right now
because we're logged in we don't need the user information and we also don't need any
shipping data because there's no products that need it so we'll minimize this a little bit here
and I'm gonna click make payment we're gonna see that data set so transaction complete
the data was sent and once that's done we are redirected back to our home page here is a
data that was printed out so that worked exactly like we wanted it to so what we want to do
now is in the next step is start start working with that data so we're first going to import
date time then we want to create a transaction ID so there's many different ways we can
create a transaction ID I'm just gonna use a time stamp we're gonna set that value and
we're gonna continue from there so let's first import date time into our view and then we'll
set the transaction ID with date time and then we're gonna set the time stamp so I want to
go back here will just import date time and down interview this is where we can set it now
so I'll remove this print statement and we're gonna say transaction underscore ID and that's
gonna be date time dot date time and we're gonna get the current value so dot now and
then we're gonna say dot timestamp so this will give us that that long character field there
so time stamp and that's also a function so I want to make sure we got that right daytime
daytime dot now timestamp so we have the time stamp and now we can move on to setting
up our conditional for our authenticated users and guest users so remember now an
authenticated user and a guest user can purchase an order so we need to create that
statement and we're gonna say if request dot user dot is underscore authenticated and
once they're authenticated we want to get the customer and we're gonna get the customer
by just getting request dot user dot customer and then before we finish this off let's just set
the else condition and for this we're just gonna print out user is not logged in so user is not
logged in and back to our request we need to get the order so we're gonna use the get or
create method so what I'm gonna do is actually copy this value here and we're gonna take
that from our update item view and if we don't have the value we want to make sure we
create it we set the customer and we need to get the order that has the value of complete
to false so we got the order we want to get our total now and we also need to parse the
data too so I forgot to do that let's set the value of data and that's gonna be json dot loads
and we're gonna throw in request body so we want to parse that data and then we want to
access it so now that we have data or fix that we can get data and then we can get that total
so we're gonna get the total by setting the variable total to data and then we're gonna get
the form so remember how we passed in our data we string to fight it so now that we
parsed it we sent the form and that's gonna be the user data so we need to get the form
value and then once we have that we can get the user object within it and the total so we
want to get this specific value right here so we're gonna say form and then we're gonna
access total so our variable of total is now whatever we passed in here and I want to set that
to a float field just in case so sometimes it might send it as a string value just to ensure that
it's correct we'll set it to a float field and then we can set our order transaction ID so we're
gonna say order dot transaction ID or transaction underscore ID and then that's gonna be
the value that we just sent here so we set our order value for the transaction ID and now
what we want to do is check if the total passed in from the front end is the same as our car
total so somebody brought this up as a comment in one of my videos and I had the solution
but I figured out show it to you guys here because our paypal information will be processed
on the front end but then sent to the back end so right now we want to make sure that a
user does not manipulate the data from the front end because in theory if they know a little
bit of Java Script and they can figure out how we built our website they can manipulate that
and get a product for a value that they want to send so what we want to do is first check if
the total that was passed in is the same as our car total if it's true then we'll just go ahead
and set complete to true and we'll save that order so let's take care of that it's a pretty
simple statement here and that's going to be done right here so we're gonna say if total is
equal to order dot get underscore cart total here we want to say order dot complete and
that's going to be set to true now so we'll set it to true and regardless of whether the total is
correct or not will still save it so if the value was incorrect we'll still save it complete will
remain false but now we can save the order and confirm it and then we can set up any other
way we want to check if a user has manipulated that data or just check that cart value and
make sure everything's correct so the last thing we want to do for an authenticated user
and this is the last step in the module is to set the value of our shipping so we want to
create some logic so after our cart total we want to check if shipping is true if it's true let's
go ahead and create the shipping address and we'll set all of the values so we sent it in from
our post request and we want to set that now so we'll say if order dot shipping if that is
equal to true let's go ahead and create the shipping address object so shipping address this
is the model now so we can do shipping address objects dot create and we can just create
all the attributes so first we're gonna set the value of customer and I'm gonna pull up the
models dot py file make sure we can see this we need to set a customer an order address
city state zip code and date added will be automatic so in here we'll just set customer to the
value of the customer then we want to set order and that is going to be the order that we
just created so we're just attaching everything and for our address we can just use that form
data that we sent in so for the address we set the form data to this object and then we
passed it in so we first need to access shipping and then access the fields in here so we'll
take in address city and state so we can do that by grabbing this data that we parsed and
earlier we grabbed the form so now we want to grab shipping because that is what we
called that attribute so we're gonna take and shipping and we want to take in address so
let's go ahead and repeat this a couple more times for our their fields here we'll add in the
comma and we'll paste us in for city state and zip code and we'll change these values so
we'll set city will change the value there we want to take in state so I'll change that up right
there and zip code so that should do it for the shipping address so we want to test this by
going to our page and checking out and we want to add an item that has the shipping
address so we can actually make sure it gets created so if we go to our website here let's
refresh it and I want to go to the admin panel and make sure that we don't have any
complete orders or a shipping address so right now we have an order here and by default it
got created because we need to set up an order with a status of false for now so the status
was set to false and or a completely set to false and then we want to go to shipping
addresses so we have none right now and we want to add an order with where we want to
add an item to our cart that needs to be shipped we'll go to our checkout page now that
we're prompted for it we can go to continue hit make payment we should be able to be
redirected to our checkout page let's see what's going on here for some reason it's not
redirecting us so in our console it looks like we spell from instead of form so for the total
this needs to be form and we should be able to give this one more test and we should be
able to place that order now so give it a second here let's add in our shipping address
continue and make payment so we get sent back to the home page if you look at our cart
we should see this reset to zero eventually but I guess that our order total so it looks like
we're not updating this cart total correctly so we're not setting the value to complete and
that is probably because the order total is different from the cart total because of what we
did in our checkout page so right now the numbers go beyond to two decimal points to the
right so what we're going to do is remove this because we're not displaying it anyway so
there was no need to format that so I'm gonna get rid of that and we'll save it and now
when we compare our get cart total they should be an exact match and we shouldn't have
an issue with the decimal places exceeding a certain amount so let's save that and I'll make
sure to for anybody following the steps I'll make sure to update the steps so we're not
showing that float format and we'll fix things like that so let's go ahead and try that one
more time we'll go to our cart we'll check out we'll add an address here go through make
payment and now our order is complete if we go to our shipping addresses this is the
second time we added it so it looks like it added it on the first round and we also completed
our order so if we go to our first order the status was set to complete we set the transaction
ID and we automatically create a new order when we go back to that home page the reason
why we created a new order is because in our store view right here we need to query in
order to be able to show a car so if we don't have one we just create it by default and that's
how we check out without the payment integration in the next video what we're going to do
is handle the unauthenticated users side of things so we want to be able to create our car in
the cookies and then allow a user to checkout so all these areas that we left blank here so
for these sections right here we actually want to start building that users order and prepping
us for checking out.

Hey everyone, I wanted to share a solution for the CSRF token issue that some users might
encounter during guest checkouts, especially on the first submission or when using
incognito mode.
Let me present two possible solutions:
Quick Fix:
I added the @csrf_exempt decorator from Django to the checkout view. This decorator
informs Django that we don't require a CSRF token for this specific view. While this provides
a temporary solution, it's important to note that we are not dealing with highly sensitive
data in this particular scenario.

More Secure Approach:


For a more robust solution, I introduced a CSRF token to our form. I included an input field
in the HTML form, and then, in the JavaScript, I retrieve the CSRF token from the form and
set it in the headers before submitting the data. This ensures a token is always available,
even if not generated in the traditional Django way.

These solutions should help address the CSRF token issue during guest user checkouts. I'll
continue to investigate the root cause for a more permanent fix in future videos or
standalone content.

If you encounter the CSRF token issue, feel free to refer back to this explanation and choose
the solution that fits your requirements. I appreciate your understanding, and let's proceed
confidently into video number five. See you there!

Hello, in this video, we're diving into the implementation of guest user checkout
functionality, enabling users without an account to build and process orders seamlessly.

Firstly, we've made a crucial update to our product model, switching the 'float' field to
'decimal' for more accurate handling of currency-related data.

Now, let's address the CSRF token issue that might affect guest users during checkout.
We've applied two solutions. The quick fix involves using Django's @csrf_exempt decorator
on the checkout view. Although it's a temporary measure, it allows us to proceed without
CSRF token verification.

For a more secure and long-term solution, we've introduced a CSRF token into the form by
adding it as a hidden input field. JavaScript retrieves this token from the form, ensuring its
inclusion in the POST data during checkout.

Now, onto the main focus of this video – implementing guest user checkout capabilities.
We'll start by handling the CSRF token issue and ensuring a smooth checkout process for
unregistered users.

To accommodate this, we're using cookies instead of session storage. Cookies offer
persistent storage across sessions, allowing users to revisit the website and retain their cart
data.

Before diving into the steps, I'd like to highlight the importance of understanding JavaScript
for full-stack developers, particularly Django developers. JavaScript proficiency is crucial for
scenarios like these, where dynamic client-side interactions play a pivotal role in enhancing
user experience.
Now, let's get into the steps:
Step 1: Setting Cookies and Creating the Cart
We've created a JavaScript function, getCookie, responsible for retrieving cookies from the
browser. If the cart cookie doesn't exist or is undefined, we create it using document.cookie.
This cookie contains a serialized representation of our cart object.

Step 2: Adding and Removing Items from the Cart


We introduced the addCookieItem function, triggered when a user clicks on the "Add to
Cart" button. This function handles both adding and removing items. The cart is structured
as an object, and the product ID serves as the key. If the item is already present, the
quantity is incremented; otherwise, a new entry is created.

Additionally, we've implemented logic to decrease the quantity or remove an item entirely.
If the quantity drops below 1, the item is removed from the cart.
This approach ensures that guest users can seamlessly manage their shopping carts, even
without an account. We're laying the foundation for a robust guest checkout system that
enhances overall user convenience.

Feel free to follow along with the code provided in the description. Let's proceed with
confidence into the next steps of our development journey.

We are continuing the development of guest user checkout functionality for a web
application. The focus is on updating the order information based on the items present in
the user's cart.
Here's an explanation of the main steps:

Getting Cookies and Parsing:


We start by obtaining the 'cart' cookie, which stores information about the items in the
user's cart.
If the cookie is not found, a default empty dictionary is created to avoid errors.

Looping Through Cart Items:


We iterate through the items in the user's cart, where each item is represented by a key-
value pair in the dictionary.
The key represents the product ID, and the value represents the quantity of that product in
the cart.

Querying Product Details:


For each product in the cart, we retrieve details from the database (e.g., price, name,
imageURL) using the product ID.
This involves querying the 'Product' model in the Django application.

Calculating Totals:
The total cost for each product is calculated by multiplying the product price by the quantity
in the cart.
This total is added to the overall order total.

Updating Order Dictionary:


The 'order' dictionary is updated with the calculated total and the quantity of items.
Additionally, details of each item, including the product details, quantity, and total, are
appended to the 'order_items' list within the 'order' dictionary.

Rendering Order Information:


The updated 'order' dictionary, containing total order information, is passed to the template
for rendering.
This information can then be displayed on the front end, providing users with a summary of
their order.
Overall, these steps involve dynamically updating the order details based on the items in the
user's cart, ensuring accurate representation and calculation of the order's total cost and
item quantity.

Updating Order Totals:


The code focuses on updating order totals dynamically based on the items in the user's cart.
The order object is constructed with total values, representing a simulated order.

Building Cart Items for Guest Users:


For guest users, a loop iterates through the items in the cart.
Each item is represented as a dictionary with nested attributes for product details (ID, name,
price) and item details (quantity, total).
These item dictionaries are appended to the 'order_items' list.

Checking Product Existence:


A check is introduced to verify if the product queried from the database still exists.
If the product is not found, the code gracefully handles this situation, preventing errors.

Handling First Load Scenario:


For scenarios where the 'cart' cookie is not present (e.g., first load), a default empty
dictionary is created to avoid errors.

Guest User Checkout Simulation:


The code simulates the checkout process for guest users by dynamically updating the order
and cart information without storing it in the database.
Organizing Code into a Utility Function:
To enhance code organization and reuse, a utility function named 'cookie_cart' is
introduced.
This function encapsulates the logic for updating order totals, building cart items, and
handling product existence checks for guest users.

Preparing for Code Cleanup:


The need for code cleanup and reusability is acknowledged, and plans are outlined to create
a 'utils.py' file.
The 'cookie_cart' function will be moved into 'utils.py' for easy integration into multiple
views.

Ensuring Functional Consistency:


The goal is to ensure that functionalities, such as updating cart totals and handling product
existence, remain consistent across different views (e.g., checkout, store).
Addressing Shipping Status for Physical Products:

The shipping status in the order is updated based on the 'digital' attribute of a product.
If a product is physical, the shipping status is set to true, indicating the need for shipping
during checkout.

Demonstrating Checkout Functionality:


The provided example shows how the cart and order information is presented on the cart
page.
Guest users can update quantities and see the corresponding changes in the cart icon.
In summary, the code orchestrates a functional and dynamic cart system for guest users,
simulating a checkout process without storing data in the database. It aims to enhance code
organization for future scalability and maintenance.
In this section, the focus is on optimizing and modularizing the existing code by introducing
a utility function named cart_data in the utils.py file. This function is designed to
encapsulate the logic related to cart and order data retrieval. The goal is to make the views
cleaner, more modular, and easier to maintain.

Creation of cart_data function:


A new function, cart_data, is introduced in the utils.py file.
This function takes the request parameter to access user-related information.
The function's return value is a dictionary containing cart items, order details, and other
relevant data.

Importing cart_data into Views:


The newly created cart_data function is imported into the views.
This enables the views to utilize the functionality provided by the cart_data function.

Refactoring Checkout View:


In the checkout view, the existing logic within the if-else block is removed.
The cart_data function is called with the request parameter, and the result is stored in the
variable data.
The view now accesses the required information, such as cart items, order details, and
items, from the data variable.
Refactoring Cart View:
Similar to the checkout view, the cart view undergoes refactoring.
The if-else block is removed, and the cart_data function is called with the request
parameter.
The view now accesses car_items, order, and items from the data variable.

Refactoring Store View:


In the store view, the logic related to cart and order data retrieval is replaced with a call to
the cart_data function.
Only the necessary information, cart_items, is retrieved from the data variable.

Code Simplification and Reusability:


The refactoring process results in cleaner views by eliminating repetitive logic and
simplifying the code structure.
The cart_data function encapsulates the complexity of data retrieval, promoting code
reusability across different views.

Ensuring Consistency:
The introduction of the cart_data function ensures consistency in the way cart and order
data are handled across various views.
The same set of information is accessed and utilized uniformly in the views.

Improved Code Organization:


The separation of concerns is achieved by moving the logic for cart and order data into a
dedicated utility function (cart_data).
This promotes better code organization and makes it easier to manage and maintain.
In summary, the refactoring process involves the creation of a utility function (cart_data) to
handle cart and order data retrieval. The views are then modified to call this function,
resulting in cleaner, more modular, and consistent code. The utility function enhances code
reusability and contributes to improved code organization.
the focus is on completing the checkout process for guest users. The steps involve clearing
cookies upon checkout and processing the order on the backend.

Clearing Cookies on Checkout:


In the checkout.html page, within the JavaScript code, there's a function triggered upon
form submission.
Before redirecting the user, the tutorial adds a step to clear the cart cookies by setting the
cart value to an empty object using document.cookie.
This ensures that the user starts with an empty cart upon their next visit.

Processing Order for Guest Users:


In the views.py file, specifically in the process_order view, the tutorial addresses the logic
for guest users.
It starts by checking if the user is authenticated. If not, it proceeds with processing the order
for guest users.
The form data is accessed, including the user's name and email.

Handling Customer Data:


The tutorial then retrieves the cart data using the cookie_data function, similar to previous
steps.
The customer is obtained or created using the email from the form data. If the customer
already exists, their information is updated; otherwise, a new customer is created.
The name from the form data is set to the customer's name.
Creating Order and Order Items:
An order is then created using the order model. The status is set to incomplete initially.
A loop is initiated to iterate through the items in the cart. For each item, the associated
product is queried from the database.
An order item is then created, linking it to the product and the order.
This ensures that each product in the cart is connected to the order.

Order Completion:
The status of the order is set to incomplete initially to signify that payment processing is
pending.
The tutorial doesn't cover the payment processing part in this module but sets the
groundwork for future integration.
Customer Reusability:
A notable feature is the use of the get_or_create method for customers. If a guest user with
the same email returns, the system recognizes them as the same customer.
This approach avoids creating multiple user accounts for the same guest user and allows for
smooth tracking of their orders.

Database Organization:
The tutorial ensures proper organization in the database by linking orders, order items,
customers, and products together.
Each order item is associated with a specific product and belongs to a particular order.

Completing the Checkout Process:


Although payment processing is not covered in this module, the groundwork is laid for
future integration.
The tutorial ensures that the backend logic for completing the order is in place, and the
order is appropriately associated with the products in the cart.
In summary, Part 6 concludes the checkout process by clearing cookies upon submission and
processing orders for guest users. The tutorial provides a robust foundation for handling
orders, connecting them to customers, and organizing data in the database. The completion
of the checkout process sets the stage for the next module, which involves payment
integration.
In this section of the tutorial, the focus is on organizing and optimizing the code within the
views. Here are the main steps:

Function Extraction:
The tutorial starts by recognizing that the logic for guest checkout can be encapsulated
within a function to enhance code readability and maintainability.
A new function named guest_order is created in the utils.py file, accepting request and data
as parameters and currently returning an empty string.

Code Transfer to Function:


The entire logic within the else statement of the original view is then cut and pasted into the
new guest_order function.
This includes processing customer and order creation, handling shipping details, and
managing the order items.

Function Invocation:
Back in the original view, the guest_order function is called within the else statement where
guest users are processed.
The function is invoked with the required parameters (data and request), and the returned
values (customer and order) are stored.

Verification and Testing:


The tutorial emphasizes the importance of confirming that all necessary values, such as
customer and order, are still accessible after the function call.
The verification ensures that both authenticated and guest users have their respective
orders processed correctly.

Database Confirmation:
To validate the functionality, the tutorial suggests checking the admin panel for newly
created orders and customers.
A test is conducted with a guest checkout, and the admin panel is revisited to confirm the
creation of the customer and order records.

Finalization:
The tutorial concludes by acknowledging the success of both authenticated and guest
checkout processes.
It sets the stage for the next module, where payment integration will be added, specifically
incorporating PayPal for transactions.
In summary, this part of the tutorial focuses on code organization, extracting logic into a
function for guest checkout, and ensuring that the restructuring doesn't impact the overall
functionality. The modular approach enhances the clarity of the views, making them more
readable and maintainable.

the goal is to integrate PayPal checkout into a Django e-commerce website. This integration
enables users to complete transactions using their PayPal account or by submitting credit or
debit card information through PayPal. The implementation involves replacing the existing
"Make Payment" button with PayPal checkout options.

Introduction to PayPal Integration:


The video aims to incorporate PayPal checkout functionality into a Django e-commerce site.
Users will be able to finalize transactions using either the default PayPal checkout or by
providing credit/debit card details via PayPal.

Client-Side Integration with PayPal:


The video guides users through the process of integrating PayPal buttons using client-side
integration.
Viewers are directed to a specific link provided in the description, where they can find
source code for various PayPal buttons.

Setting Up a Sandbox Account:


A sandbox account is recommended for testing purposes to avoid real transactions during
development.
The tutorial briefly mentions the distinction between a sandbox and a live PayPal account.

SSL Certificate Requirement:


Emphasis is placed on the necessity of having an SSL certificate for the website to enable the
"Debit or Credit Card" option.
Without SSL, PayPal may hide this option to secure user information.
Modification in Checkout HTML:
In the Django app named "store," the existing "Make Payment" button is replaced with the
PayPal buttons.
The provided code includes an empty div with the ID "PayPal-button-container" to which
PayPal buttons will be appended.

Adding PayPal API Script:


A script tag for the PayPal API is added to the HTML to grant access to PayPal buttons.
The tutorial instructs users to place this script above the original JavaScript in the document.

Custom JavaScript for PayPal Buttons:


Custom JavaScript code is introduced, responsible for handling the creation of PayPal
buttons and their placement in the designated div.
Two main methods, namely createOrder and onApprove, are explained:
createOrder: Launches the default PayPal checkout experience, setting the transaction
value dynamically.
onApprove: Executes when the user approves the payment, making API calls to complete
the transaction.

Explanation of Button Rendering:


The custom JavaScript utilizes the paypal.buttons.create() method to render PayPal buttons
within the designated div.

Testing and Sandbox Environment:


The video encourages users to test the PayPal integration in a sandbox environment to
ensure seamless functionality.
Once satisfied, users can transition to a live environment with real client IDs linked to their
PayPal account.
In summary, the video focuses on integrating PayPal checkout into a Django e-commerce
website, providing step-by-step guidance on modifying HTML, incorporating the PayPal API,
and customizing JavaScript for seamless button rendering and functionality. Testing in a
sandbox environment is recommended before moving to a live environment.
the focus is on setting up sandbox accounts for testing PayPal transactions within the
Django e-commerce website. Two types of accounts are created: a business account
(receiver) and a personal account (representing a user shopping on the website).

Creating Sandbox Accounts:


Two accounts are needed: a business account to receive money and a personal account to
send money.
Instead of using the default account creation method, the tutorial recommends creating
custom accounts for better control over email, password, and account balance.

Account Balances:
After creating the personal and business accounts, the tutorial suggests setting a custom
account balance for testing purposes.
The account balance is set to simulate transactions during testing.

Creating an App within PayPal:


To facilitate communication between the website and PayPal, an app needs to be created
within the PayPal developer dashboard.
This involves going to the "My Apps & Credentials" section and clicking on "Create App."

Generating Client ID:


The tutorial walks through the process of generating an app, which results in obtaining a
client ID.
The client ID is less sensitive than the secret key and is used in the front-end script to
connect the PayPal buttons to the specific PayPal account.

Replacing Client ID in Script:


The obtained client ID is then inserted into the script of the Django e-commerce website.
It ensures that PayPal buttons are connected to the specific PayPal account, allowing
transactions to be directed to the intended recipient.
The significance of using sandbox accounts is emphasized, providing a safe environment for
testing transactions without involving real money. The tutorial encourages viewers to follow
these steps meticulously to ensure the correct setup for PayPal integration within the
Django website.
the focus is on testing payments with the integrated PayPal checkout on the Django e-
commerce website. Key steps covered in this section are as follows:

Testing a One-Cent Transaction:


The tutorial demonstrates testing a payment with a one-cent transaction to ensure the
connection with PayPal is functioning.
After processing the payment, the tutorial emphasizes that the transaction may take some
time to reflect in the sandbox accounts, usually around 5 to 10 minutes.

Displaying Cart Total Dynamically:


The next step involves dynamically displaying the cart total on the checkout page.
The total is retrieved from the original script tag, moved above the PayPal buttons, and
formatted using JavaScript's parseFloat and toFixed to limit decimal places to two.

Processing Orders on the Backend:


After displaying the cart total, the tutorial addresses the importance of processing orders on
the backend.
The existing submitFormData function, which sends data to the backend, is triggered after
the payment is completed.

Handling Total Manipulation Concerns:


The tutorial addresses potential concerns about users manipulating the total price on the
frontend.
It explains that the backend verifies the submitted total against the cart total to ensure
accuracy and prevent manipulation.
Live Client ID Integration:
For those transitioning to a live environment, the tutorial briefly mentions the need to
replace the sandbox client ID with the live client ID in the script tag.

SSL Certificate Requirement:


A crucial point is made about the necessity of having an SSL certificate for the website.
Without an SSL certificate, the debit or credit card option will not work, emphasizing the
importance of securing the website with HTTPS.
Completion of Checkout Process:
The tutorial completes the checkout process, demonstrating that the order is successfully
processed, the cart is cleared, and users are redirected.
Transition to Live Environment:
The final step involves transitioning to a live environment by creating a live app on the
PayPal developer dashboard and updating the script tag with the live client ID.
The video concludes with the completion of the payment integration series, and the tutorial
author hints at potential future additions to the series. Overall, the video provides a
comprehensive guide to integrating PayPal checkout into a Django e-commerce website,
from setting up sandbox accounts to testing and transitioning to a live environment.

You might also like