• No results found

You don’t need to put all your work at /var/www to see if your code runs. Django has it’s own development server, that you can run whenever you want and access via url. Just run the command:

$ python manage.py runserver

You should see the following output command line:

Validating models...

0 errors found

July 16, 2013 – 19:48:35

Django version 1.5.1, using settings ‘dbuy.settings’

Development server is running at http://127.0.0.1:8000/

Quit the server with CONTROL-C.

And, if you visit http://localhost:8000/ on your browser you should see a Welcome screen.

This is the Django development server, a Web server written in Python. Note that this server is not meant to be used to run your applications in production, it’s just to speed your development.

Initial setup

Open dbuy/settings.py. It’s a python file that represents Django settings. You’ll see database, timezone, admins, static and template configs. At first we’re going to set up the database. You’ll see a dict like this:

Listing 1.

Listing 1. A longer piece of Python code DATABASES = {

‘default’: {

‘ENGINE’: ‘django.db.backends.’, # Add ‘postgresql_psycopg2’, ‘mysql’, ‘sqlite3’ or

‘oracle’.

‘NAME’: ‘’, # Or path to database file if using sqlite3.

# The following settings are not used with sqlite3:

‘USER’: ‘’, ‘PASSWORD’: ‘’,

‘HOST’: ‘’, # Empty for localhost through domain sockets or ‘127.0.0.1’ for localhost through TCP.

‘PORT’: ‘’, # Set to empty string for default.

}}

You can set more than one database, but for this tutorial we’re just using one, the default one. The keys represent the settings of a database.

• ENGINE – What database you’ll use. Django supports officially postgresql, mysql, oracle and sqlite3.

We’re going to use sqlite3.

• NAME – Your database name. In our case, the name of the file.

• USER – Your database username. Not used in sqlite3.

• PASSWORD – Your database password. Not used in sqlite3.

• HOST – The host your database is on. Not used in sqlite3.

So, our settings will be like this: Listing 2.

Listing 2. A longer piece of Python Code DATABASES = {

‘default’: {

‘ENGINE’: ‘django.db.backends.sqlite3’, ‘NAME’: ‘database.db’,

}}

Take a look at INSTALLED_APPS setting. A tuple that shows all Django applications that are activated in your project. You can create your own pluggable apps, package and distribute them to other developers.

INSTALLED_APPS already comes with some apps, already included in Django. You can install other apps, made by others or by yourself. Also, you can create your own pluggable apps, package, and distribute them to other devs.

With the database configured, let’s create our database. At your shell, type:

$ python manage.py syncdb

This command will see all the INSTALLED_APPS and create all the necessary tables for your database.

Creating your apps

You’re developing an e-commerce, so what should you have? In your e-commerce you’ll just have a list of products, that can be grouped by categories and can be bought by a customer. So let’s start implementing the products. In your shell, type the following command.

$ python manage.py startapp products

A new directory has been created on your project folder.

.├── database.db

├── dbuy

│ ├── __init__.py

│ ├── settings.py

│ ├── urls.py

│ ├── wsgi.py

├── manage.py

└── products ├── __init__.py ├── models.py ├── tests.py └── views.py

A Django app is a python package, with some files, that follows some conventions. You can create the folder and the files by yourself but the ‘startapp’ command eases your life. The next step is to write your models to define your database. Our products will have name, photo, description, price and categories. The categories

can be implemented in two ways: as a field of the product or as another model. At first we’re going to do as a field. Your products/models.py should look like this (Listing 3).

Listing 3. A longer piece of Python code from django.db import models

class Product(models.Model):

CATEGORIES_CHOICES = (

(‘eletronics’, ‘Eletronics’), (‘clothes’, ‘Glothes’), (‘games’, ‘Games’), (‘music’, ‘Music’), )

name = models.CharField(max_length=200) description = models.TextField()

photo = models.ImageField(upload_to=’uploads/products’, blank=True) category = models.CharField(max_length=30, choices=CATEGORIES_CHOICES) price = models.DecimalField(decimal_places=2)

In django, a model is represented by a class that inherits from django.db.models.Model. The class variables represent the fields of the table created by the ORM. Each field is represented by an instance of a Field class.

By default all these fields are required, if you want to set an optional field you should explicitly say this, by using the parameters blank and null.

Some fields, like DateTimeField, when blank (not required) must be null, so if you just set as blank and don’t submit the value of the field, it will raise IntegrityError, because blank is allowed but null is not. You should avoid using null=True on string based fields because doing that you allow two possible fields for “no data”:

Null and the empty string.

Some fields have required arguments, e.g. max_length in CharField, the max_digits to the DecimalField and

upload_to in the ImageField. We’ll talk about it later.As you can see we used the parameter choices on the categories. The choices parameter (optional) must receive an iterable object, of iterables of exactly 2 items (e.g. [(A,B), (C,D)])). The first one is the value that will be stored on the database, the second one is meant for humans.

What you just wrote gives you a lot of information, with the ORM, this class describes your database table and gives you access to it, but you need to activate it before. In dbuy/settings.py, add your app to the

INSTALLED_APPS tuple: Listing 4.

Listing 4. A longer piece of Python Code

# ‘django.contrib.admin’,

# Uncomment the next line to enable admin documentation:

# ‘django.contrib.admindocs’, )

And then run the syncdb command.

$ python manage.py syncdb

You’ll see that your product table was created, and now let’s play a little bit with the database.

We’re going to use python shell through the manage.py, that way the Django environment is autoloaded on your shell.

>>> p = Product(name=”Pacman”, description=”some description”, price=12.99, categories=”games”)

# just created your product

But this representation isn’t the best one. You can set on your models another way to represent your products

class Product(models.Model):

...

def __unicode__(self):

return self.name

That way you can see better your object.

>>> Product.objects.all() [<Product: Pacman>]

Let’s deal with these objects in a better way than the command line. Django already comes with an admin

interface that eases a lot your development. You just need to uncomment three lines and the admin is enabled! On your dbuy/urls.py uncomment the following lines:

# from django.contrib import admin

# admin.autodiscover()

...# url(r’^admin/’, include(admin.site.urls)),

And in your dbuy/settings.py, uncomment django.contrib.admin, into your INSTALLED_APPS. Just run the syncdb command again and and you just created a whole admin site, ready to manage your data. Let’s see what we have.

You can login with your username and password that you created in the first syncdb.

Let’s register our model in the admin. I like to create a file admin.py for each one of my apps, and there, register the models of the app. For the products app it should looks like this:

from django.contrib import admin from products.models import Product

admin.site.register(Product)

Now you’ll be able to edit your products. The Django admin is a powerful tool and you can personalize it, read the admin docs https://docs.djangoproject.com/en/1.5/ref/contrib/admin/ to suit the admin to your needs. We’re ready to put something in our home page, at least a list of our products.

Writing your first views

Open your dbuy/views.py and write the following code:

from django.http import HttpResponse def index(request):

return HttpResponse(“Welcome to D-Buy Store!”)

You just created the index view, it just receives an HTTP request and returns a response, but by itself doesn’t do anything, you have to set the urls to ‘find’ the view. On your dbuy/urls.py add the following code:

url(r’^$’, ‘products.views.index’, name=”index”),

Now you just need to visit the application on your browser to see your Hello World there. In the urls the first parameter is a regex that represents the actual url, the second one is the path to the view that will be called and the third one is an alias that we’ll use later.

What if i want to see the list of the products? You should start to work with the context. The context is a dictionary mapping template variable names to Python objects. Now your view should look like this: Listing 5.

Listing 5. A longer piece of Python Code from django.http import HttpResponse

from django.template import RequestContext, loader from products.models import Product

def index(request)

products = Product.objects.all()

template = loader.get_template(‘index.html’)

context = RequestContext(request, {‘products’: products,}) return HttpResponse(template.render(context))

This will get all your products and render the template. When the render function finds a template variable

‘products’ it will associate with the python variable. But for this code works you have to write your templates.

On settings.py, find the variable TEMPLATE_DIRS and add the path to your template dir. It’s highly recommended that you don’t hardcode it. Most of the time you’re working, you read someone’s else code, so you need a dynamic configuration for any os (Listing 6).

Listing 6. A longer piece of Python code

from os.path import abspath, dirname, join PROJECT_ROOT = dirname(abspath(__file__)) TEMPLATE_DIRS = (

join(PROJECT_ROOT, ‘templates’), )

Listing 7. A longer piece of HTML code

<html>

<p> For more information please send an e-mail to [email protected] </p>

</body>

</html>

That way you ensure that the path is always gonna be right for any OS and any path. Now, in the same folder of your settings.py, create a folder named ‘templates’ and create a file ‘index.html’, and start writing your first HTML page (Listing 7).

Now, run your server and access the url http://localhost:8000/.

You should see something like this: