Beginning Django E Commerce
398 pág.

Beginning Django E Commerce


DisciplinaProgramação I24.414 materiais278.198 seguidores
Pré-visualização50 páginas
Cart IDs: 
www.it-ebooks.info
CHAPTER 4 \u25a0 THE SHOPPING CART 
 
86 
 
import random 
 
def _generate_cart_id(): 
 cart_id = '' 
 characters = 'ABCDEFGHIJKLMNOPQRQSTUVWXYZabcdefghij \ufffd 
 klmnopqrstuvwxyz1234567890!@#$%^&*()' 
 cart_id_length = 50 
 for y in range(cart_id_length): 
 cart_id += characters[random.randint(0, len(characters)-1)] 
 return cart_id 
I should point out that the random module is not actually \u201crandom\u201d enough for serious security 
purposes, but it\u2019s random enough for our purposes in trying to make sure two poor shoppers out there 
don\u2019t end up with the exact same Cart ID. Each of our generated Cart IDs is 50 characters in length, and 
with 72 possible characters for each of the 50, there are 5072 possible Cart IDs\u2026 which is really a lot of 
Cart IDs. This makes the likelihood of a collision extremely improbable. 
Of course, we cannot say with absolute certainty that no two customers will ever end up with same 
Cart ID, but the chances are so remote that for practical purposes, we don\u2019t need to worry about it. You 
can rest easy knowing that the guy trying to buy a death metal distortion pedal doesn\u2019t end up with a 
harmonica in his cart, and vice versa. 
Using Django Forms 
When you get right down to it, web developers probably enjoy creating, designing, and testing forms for 
usability about as much as users enjoy clicking around them. They\u2019re clunky, awkward, and there\u2019s not a 
lot of room for creativity. They\u2019re a functional requirement. You\u2019re users have to be able to add items to a 
cart and give you their order information, or else you\u2019re not going to be able to make any money. 
Django has an interesting approach for dealing with forms: create a Python class, much like you did 
with your models, that represents a form, instantiate one in your view code, and pass it to your template 
just like you would any other variable. 
If that sounds a little odd, don\u2019t worry. It is a rather unique approach to creating forms, but once you 
get used to it, you\u2019ll be amazed at the amount of flexibility you have in using them to create forms for 
your user interface. The first form we\u2019re going to create will be the \u201cAdd to Cart\u201d form on the product 
page. It\u2019s just a baby, with only a small handful of inputs. 
The Add To Cart Form 
I mentioned the use of cookies earlier in the chapter. One caveat is that cookies are not always enabled 
in the user\u2019s browser by default. It\u2019s very easy for a user to turn them off so a site cannot write cookie 
values to their machine. 
Our site requires that customer\u2019s surfing our site must have their browsers configured in order to 
accept cookies. Since our site requires that cookies be enabled before anyone can add anything to the cart, 
we need to check to see if cookies are enabled and, if they are disabled, display a message to the customer 
letting them know that they need to enable cookies in their browser before they can use our site. 
This may sound kind of Draconian, like \u201cTurn on your cookies or get lost,\u201d and I understand your 
concern. You don\u2019t want to annoy anyone, but if I were you, I wouldn\u2019t worry too much. These days, 
almost everyone has their cookies enabled, and almost every site requires them. If you don\u2019t believe me, 
go ahead and turn your own cookies off, and try browsing the web for a while. You\u2019ll get an error 
message from just about every reputable site that has a login or a shopping cart. 
www.it-ebooks.info
CHAPTER 4 \u25a0 THE SHOPPING CART 
 
87 
 
For the most part, this shouldn\u2019t be an issue for you, but you do want to make sure that if any super-
paranoid, hacker-fearing customer tries to add something to their cart, they get some feedback about 
why their attempt to add to the cart didn\u2019t work. 
As it turns out, Django has the plumbing built right in to test whether cookies are available. You can 
write a test cookie to the user\u2019s browser, which you can then check for to make sure it exists, and delete it 
when you\u2019re done using it. 
To write this dummy test cookie, we use the following line of code: 
request.session.set_test_cookie() 
Then, when you need to check for that cookie\u2019s existence in your code, you use the following 
function, which will check for the cookie and return True if it finds it: 
request.session.test_cookie_worked() 
Lastly, you can destroy this dummy cookie with: 
request.session.delete_test_cookie() 
We\u2019re going to use these three methods in our form code to check if cookies are enabled and, if they 
aren\u2019t, let the user know they can\u2019t buy anything from our site until they are enabled. 
Go back into your catalog app directory and find the file called forms.py. Open it up and add the 
following class definition for our \u201cAdd To Cart\u201d form, below the ProductAdminForm class: 
from django import forms #this import should already be at the top 
 
class ProductAddToCartForm(forms.Form): 
 quantity = forms.IntegerField(widget=forms.TextInput(attrs={'size':'2', \ufffd 
 'value':'1', 'class':'quantity', 'maxlength':'5'}), \ufffd 
 error_messages={'invalid':'Please enter a valid quantity.'}, 
 min_value=1) 
 product_slug = forms.CharField(widget=forms.HiddenInput()) 
 # override the default __init__ so we can set the request 
 def __init__(self, request=None, *args, **kwargs): 
 self.request = request 
 super(ProductAddToCartForm, self).__init__(*args, **kwargs) 
 
 # custom validation to check for cookies 
 def clean(self): 
 if self.request: 
 if not self.request.session.test_cookie_worked(): 
 raise forms.ValidationError("Cookies must be enabled.") 
 return self.cleaned_data 
Each field definition in the form class is assigned a given field type, based on the type of data you are 
asking the user for. These fields take a \u201cwidget\u201d argument that allows you to control exactly how the 
input is rendered on the page. As you can see, this is a very simple form that only takes a quantity that 
the user can input, and a hidden input field that represents our product slug to identify just which 
product is being added to the cart. 
The quantity field will be rendered as a textbox input to the user, with some extra attributes like size, 
value, and class. We\u2019ve also specified a custom error message that will be displayed to the user if they try 
and submit the form with an invalid value. 
www.it-ebooks.info
CHAPTER 4 \u25a0 THE SHOPPING CART 
 
88 
 
The hidden input will never be displayed, so we don\u2019t have to waste valuable CPU cycles in our 
brain determining how it should look on the page. We\u2019re just going to assign it a value in our view code, 
just before we pass it to our templates. 
Following the field definitions are two function definitions. The first one overrides our form\u2019s 
default constructor with its own __init__() function definition, which enables us to pass the current 
request object into our form instance, so we can check to see if cookies are enabled. 
The second function definition, clean(), is called on our form to actually perform the validation. If 
cookies are disabled in the user\u2019s browser and test_cookie_worked() returns False, then we raise a 
ValidationError with a quick message letting the user know they need to enable cookies to shop our site. 
Processing the Form 
The HTTP protocol, the one sending web pages from servers to client machines all over the world, uses 
different verbs in order to process requests. There are two verbs that are in widespread use: GET and 
POST. These are really not so much like verbs as they are adverbs, in that they are defining how we are 
requesting instead of changing the action itself. The majority of the time, the GET verb is the one being 
used. When you click a hyperlink