Beginning Django E Commerce
398 pág.

Beginning Django E Commerce


DisciplinaProgramação I24.421 materiais278.260 seguidores
Pré-visualização50 páginas
you mentioned last 
month. Please reconsider my advice for seeking gainful employment. Sincerely, Arnold.\u201d You see? With 
that reply, he addressed not only the letter I had sent but the one before it as well. The response feels 
more personal, like he\u2019s really listening to me, and I really get the impression that he cares. 
You want your customers to think, and know, that you care. Web developers have been using a 
technique to identify and track all of those anonymous requests that come in from web surfers for a long 
time now, using cookies. A cookie is a small text file that you write to each user\u2019s computer, via their 
browser, with some information that you can use to uniquely identify that user on that computer. We 
can use this for all sorts of things that will let us tailor the experience that the user has on our site 
specifically for them. 
The beauty of this approach is that it allows customers who aren\u2019t registered or logged in to still 
shop on our site, adding items to their cart for eventual checkout. This is the best approach, because you 
want to make everything as easy as possible for your users, particularly the new ones. If you concern new 
users with registering before they can even start shopping on your site, you\u2019re going to annoy some of 
them and they\u2019re going to leave. Just because the register-first-then-shop approach works for Costco 
certainly doesn\u2019t mean it\u2019s a good idea for your site. 
We\u2019re going to use this cookie information to help track the shopping cart data. When a user first adds 
an item to their cart, we\u2019re going to create a long and crazy string of random characters that will uniquely 
identify their cart and the items in it, and write this to a cookie in their browser. Then we\u2019ll store this long 
string with the associated cart items in the model. Whenever they interact with their cart, or add other 
items to it, we\u2019ll reference this identifier to pull the corresponding cart items from the database. 
There is an important distinction to point out here, about how we\u2019re using session information. 
There are lots of examples floating around out on the Internet that demonstrate how to use sessions in 
Django, and while the examples are programmatically correct, they are architectural nightmares that, if 
implemented, wouldn\u2019t scale at all. 
Let\u2019s say you want to restrict product reviews to one per product per customer on the site, and you 
decide to use the Django session framework in order to track which products a user has reviewed to 
prevent them from posting more than one for any given product. Now, what you don\u2019t want to do is 
write a cookie for each product that the user reviews and track them that way. There is a limit to how 
many cookies you should be writing to each user\u2019s browser, and in practice, it\u2019s somewhere between 30 
and 50 cookies. (As a matter of fact, the number of cookies you actually use will likely be much smaller 
than that.) Since a user might write hundreds of product reviews (in theory), filling up a user\u2019s machine 
with hundreds of corresponding cookies is bad architecture. 
Admittedly, this is a poor example, because you would more than likely track a user\u2019s reviews with 
an e-mail or a user account. My only point is that sessions are one tool in the Django arsenal, they can be 
used for tracking anonymous users, and you certainly don\u2019t want to start storing large quantities of 
detailed information in them. That\u2019s what your database is for. 
www.it-ebooks.info
CHAPTER 4 \u25a0 THE SHOPPING CART 
 
82 
 
The Shopping Cart Model 
Let\u2019s continue this chapter with a very quick review of setting up models, just like we did in the last 
chapter. Before we get started, I\u2019d like to remind you that source code for this chapter can be 
downloaded from the Apress web site, if you want to spare your wrists some mileage at the keyboard. 
First, we\u2019re going to create a new app within our project to house all of the shopping cart 
information. I\u2019m going to call my app cart. 
From the root of your project, run the following: 
$ python manage.py startapp cart 
This will create the directory with the default Django app files, and that\u2019s just so Chapter 3 that I\u2019m 
not going to repeat the list again for you here. 
First, let\u2019s talk about what we need for our shopping cart models. What data do you need to store? 
Turns out this requires a little more thought than the product data, and once again, I welcome you to 
sketch up a mock of what you envision your cart should look like and go from there. Here\u2019s one hint: 
don\u2019t store any information that\u2019s associated directly with the product (like the price) or anything that\u2019s 
calculated (like the extended price) in the cart models. 
For my simple little cart model, I came up with four things that I need to store with each item in a 
user\u2019s shopping cart: 
1. Our unique Cart ID value 
2. Product ID 
3. Date product was added to the cart 
4. Quantity in the cart 
This is simple. Exceedingly simple. It\u2019s so straightforward that we really only need one model for 
storing this information. Open up your models.py file in your new cart app and add in the following 
code for your cart item class: 
from django.db import models 
from ecomstore.catalog.models import Product 
 
class CartItem(models.Model): 
 cart_id = models.CharField(max_length=50) 
 date_added = models.DateTimeField(auto_now_add=True) 
 quantity = models.IntegerField(default=1) 
 product = models.ForeignKey('catalog.Product', unique=False) 
 
 class Meta: 
 db_table = 'cart_items' 
 ordering = ['date_added'] 
 
 def total(self): 
 return self.quantity * self.product.price 
 
 def name(self): 
 return self.product.name 
 
 def price(self): 
 return self.product.price 
 
www.it-ebooks.info
CHAPTER 4 \u25a0 THE SHOPPING CART 
 
83 
 
 def get_absolute_url(self): 
 return self.product.get_absolute_url() 
 
 def augment_quantity(self, quantity): 
 self.quantity = self.quantity + int(quantity) 
 self.save() 
As you can see, the CartItem class and its associated methods borrow a lot from the related Product 
model. When we call the name, price, and the link to the cart item, we\u2019re actually going to be calling for 
those items on the related product that we\u2019ve set up in our model as a foreign key. Items on the cart page 
will be linkable, but the items will link to the product page, since they don\u2019t have their own dedicated 
templates. There\u2019s also one method, called total(), that returns the extended price, which is calculated 
from the product\u2019s price and the quantity of the cart item. 
Now that we\u2019ve added a new model, we need to make sure that we add the new app to our 
settings.py file and run manage.py syncdb to create the database table. Open up your settings.py file 
and add the following line to your INSTALLED_APPS section: 
'ecomstore.cart', 
Then, inside your system\u2019s shell, run the following command in your project: 
$ python manage.py syncdb 
The database table for the CartItem model class should now be created and ready to start storing 
shopping cart items. 
Let\u2019s back up one step: why are we only using one model instead of two? In a cart with more than 
one item, we\u2019re going to be storing the Cart ID for that user in more than one place. In a properly 
normalized database, you\u2019re trying to reduce the amount of redundancy as much as possible, because 
you want to ensure that when the time comes to change the data, you\u2019ll only have to remember to 
change it in one place. Given this thought, it makes more sense to give the Cart ID its own table and link 
it, in a one-to-many relationship, with the items it contains. 
I\u2019ve chosen to merge the cart data into one table, and potentially store redundant