Part 5 | cartData()
Overview:
Our views look much better now that we are building our cookieCart in "utils.py" but we can always make things cleaner.
Moving all cart logic to utils.py
Let's remove this repetitive logic from all our views into its own function so we can call one function that will handle everything for us.
Essentially we will take all this logic and add it to a function called "cartData" and use that function in our views intead of writing this logic each time.
This will be exactly like we did with "cookieCart", only now we will have one function handle ALL of our cart logic for logged in and guest site visitors.
Step 1 | Create Function
00:45:40In "utils.py", let's create one more function underneath the cookie cart and call it “cartData”. Cart data will also take in "request" as a parameter.
Create function
Import into views.py
Just like cookie cart, we will use this function inside our views file so make sure to add it to our imports.
from .utils import cookieCart, cartData
Step 2 | Move view logic
00:46:49Just like we did with cookieCart, let's copy ALL of the logic from our views and paste it into cookie cart.
Copy
Paste
Make sure we are returning "cartItems", "order" and "items" so we can use these in our view later.
View Source CodeStep 3 | User cartData() in views
00:47:23Now we can use cartdata() in our views to make things MUCH cleaner. Just like we used cookieCart; let's call cartData and set the variable to "data", this time now we can just call "data" and get all the values we need.
View Source Code