Beginning Django E Commerce
398 pág.

Beginning Django E Commerce


DisciplinaProgramação I24.815 materiais282.481 seguidores
Pré-visualização50 páginas
only able to access the ecomstore database. You can 
exit the MySQL prompt by typing quit. 
 
4 http://unicode.org/ 
5 http://dev.mysql.com/doc/refman/5.0/en/charset-server.html 
www.it-ebooks.info
CHAPTER 2 \u25a0 CREATING A DJANGO SITE 
 
22 
 
If you get an error when trying to enter your MySQL shell, examine the error message that Django 
displays back at you and try to determine what the problem is. The most common mistake is to try and 
use the incorrect database information. Check your settings.py database values again to make sure 
they contain the correct database credentials. 
Dealing with Django Exceptions 
So now that we\u2019ve done all this work setting up our database, let\u2019s put it to good use for ourselves by 
getting it to log exceptions for us. An exception is an unexpected and unusual condition that causes your 
computer program\u2014whether it\u2019s a Python program or a Django web project\u2014to halt normal execution. 
This could be your site trying to do something it\u2019s not allowed to do, or perhaps you\u2019ve pointed your 
code to a file that doesn\u2019t exist. 
For practical reasons, you want to anticipate where potential exceptions might occur in your code 
and log them so you can review (and hopefully fix) them later. As good a programmer as you might be, as 
soon as you release your Django project into the wild, there is a slew of things that can potentially go 
wrong, and you want a means to track these issues. Of course, tracking these exceptions is a very good 
thing to do during development. And that\u2019s what we\u2019re going to do with our database right now. 
Thanks to the open source community, there\u2019s already a solution out there that we can use to log 
Django exceptions to our database. The package is available at http://code.google.com/p/django-
db-log/. 
Go ahead and download the code (you might need to check it out of the subversion repository as we 
discussed in Chapter 1) to a directory of your choice, navigate into the directory, and install the package 
using the standard distutils method: 
$ python setup.py install 
This will extract the code into your Python\u2019s site-packages directory. Once this is on your 
machine, there are a couple of changes you need to make to your settings.py file in order for the 
logging to begin. There are two Python tuples in your settings.py file called MIDDLEWARE_CLASSES, and 
INSTALLED_APPS. 
Add the Django DB Log middleware module to MIDDLEWARE_CLASSES: 
MIDDLEWARE_CLASSES = ( 
 'django.middleware.common.CommonMiddleware', 
 'django.contrib.sessions.middleware.SessionMiddleware', 
 'django.contrib.auth.middleware.AuthenticationMiddleware', 
 'djangodblog.DBLogMiddleware', 
) 
 
Be sure you include the trailing comma after that last item in the tuple. Items listed in Python tuples 
are delimited by commas, which is a simple concept to keep in mind. The problem comes up when there 
is a Python tuple that contains only a single item. In this case, there must be a comma after the only item 
in order for Python to recognize it as a valid tuple object. You don\u2019t need a comma after this last item, 
but it\u2019s good practice to follow every item in your tuples with a comma to get in the habit. By default, the 
INSTALLED_APPS tuple includes a few apps enabled for your convenience. However, to keep things 
simple in the meantime, we\u2019re going to disable those four and add the Django DB Log. You can 
comment out lines in your Python files by placing a # symbol at the beginning of each line you want to 
remove. Edit your INSTALLED_APPS so that it looks like this: 
www.it-ebooks.info
CHAPTER 2 \u25a0 CREATING A DJANGO SITE 
 
23 
 
INSTALLED_APPS = ( 
 #'django.contrib.auth', 
 #'django.contrib.contenttypes', 
 #'django.contrib.sessions', 
 #'django.contrib.sites', 
 'djangodblog', 
) 
Once again, don\u2019t forget the comma after the last (and in this case, only) element in the tuple. With 
this in place, hop on back to your shell and run the following command: 
$ python manage.py syncdb 
Creating table djangodblog_errorbatch 
Creating table djangodblog_error 
Installing index for djangodblog.ErrorBatch model 
Installing index for djangodblog.Error model 
If you\u2019ve set up your database, you should see a message about the creation of two tables with two 
indexes added to them. Your Django project will now log all of its exceptions to a database table called 
djangodblog_error. All we need now is an exception for our application to catch. 
Template & View Basics 
So now that we have a database in place, let\u2019s look at setting up our first custom web page by examining 
the Django templating system (more on the exception later). First, let\u2019s briefly go over how Django 
handles a request made to our site: 
1. The request comes in to the server from the client and this is routed from the 
web server to our application. 
2. The URL resolver examines the request and compares it with a set of regular 
expressions specified in the project\u2019s urls.py files, which are mapped to 
Django functions called views. 
3. The request and any additional parameters supplied by the URL are passed to 
the corresponding view function. 
4. After running whatever logic the site needs, the view function returns a 
response, which typically takes the form of a generated HTML page. 
Defining everything as simply as possible, a Django application is little more than a group of Python 
functions that take HTTP requests and return HTML responses. Your urls.py file just acts as a 
dispatcher directing what functions the requests are routed to. This may sound a little esoteric in theory, 
so let\u2019s put it into practice. 
Here\u2019s an example of a Python function that acts as a Django view (you don\u2019t have to type this in yet): 
def catalog(request): 
 site_name = "Modern Musician" 
 response_html = u&quot;<html><body>Welcome to %s.</body></html>&quot; % site_name 
 return HttpResponse(response_html) 
www.it-ebooks.info
CHAPTER 2 \u25a0 CREATING A DJANGO SITE 
 
24 
 
In this overly simple example, we create two strings, embed one in the other using the string format 
operator (the %) and Python string interpolation,6 pass them into a new HttpResponse object, and 
return it to the request. All we\u2019d need to do to make this page usable in the real world is give it a 
corresponding entry in our urls.py file, which might look something like this: 
urlpatterns = patterns('', 
 # other commented code here. 
 (r'^catalog/$', 'ecomstore.views.catalog'), 
) 
Given this, if you were to navigate to http://localhost:8000/catalog/, you would be presented 
with the welcome message you created previously. While it\u2019s probably not a code sample that will land 
you your dream job, it does illustrate the basic concept of what a Django view does. 
Naturally, in the face of such simplicity with our example, there are some very obvious drawbacks to 
this approach, which should be immediately apparent to anyone who\u2019s spent more than five minutes 
coding for the web. The first thing you should note is that we\u2019ve just hard-coded the basic HTML tags for 
our page in a Python string. Perfect for a \u201cHello World!\u201d example, but definitely not ideal for a real-world 
application. 
This is where Django templates come in. In almost all practical cases, you\u2019ll load a file in your 
project\u2019s directory into a Django Template object that you can use in your response. This file will contain 
all of the HTML markup that your page has, along with placeholders for variables. 
You\u2019ll also notice that we passed in the name of the site using the Python string formatter syntax. 
For larger pages that require a lot of variables to be passed in, this could very quickly become an 
unmanageable headache. Fortunately, Django templates manage their variables using special