Tabla de Contenidos

Django

Basic

First steps

Creating your project

$ django-admin.py startproject mysite

It will create the next file tree:

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        wsgi.py

Where important files are…

To run the server you'll need to do…

$ python manage.py runserver

You could run python manage.py runserver 8080 to run it on port 8080, or python manage.py runserver 0.0.0.0:8000 to run it on each network interface.
Each time you change your database configuration or some of the django installed apps you'll need to run:

$ python manage.py syncdb

Other django commands are:

Basic knowledge for creating applications

For django an application is like a module, something that has a concrete purpose and performs actions for that. An application can be used in several projects because a project is finally a group of applications.

$ python manage.py startapp polls

This command will create a polls application structure in your django project folder. It will create next structure folder:

To use it you'll need to add it on the settings.py file, on INSTALLED_APP block.
To add to the administration interface a concrete interface for an element in the model we will add something like that in admin.py:

from django.contrib import admin
from polls.models import Poll
admin.site.register(Poll)

The structure to arrange several applications inside a project is:

<my project>
-- manage.py
-- <project name>
----- urls.py
----- models.py
----- views.py
----- blog\ <- An app
-------- views.py 
-------- urls.py
-------- models.py
----- tasks\ <- Another app
-------- views.py
-------- urls.py
-------- models.py

Shell

Running the command $ python manage.py shell will open a Python shell to interact with data inside the project.

Configuration and settings

A settings file is just a Python module with module-level variables. So it can import values from other settings file.

Using settings in Python code

from django.conf import settings

if settings.DEBUG:
    # Do something

Remember that django.conf.settings is not a module so from django.conf.settings import DEBUG will not work.

Superuser creation

$ python manage.py createsuperuser --username=joe --email=joe@example.com

Database

Basic

To config the database engine you'll need to edit settings.py. You should change values like ENGINE, NAME, USER, PASSWORD, HOST… By default an sqlite engine is defined, however you can choose: 'django.db.backends.postgresql_psycopg2', 'django.db.backends.mysql', 'django.db.backends.sqlite3' or 'django.db.backends.oracle'.

In an app the models.py file contains all the classes that represents the model, they should be defined like…

from django.db import models
 
class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
 
class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

Field types are described in https://docs.djangoproject.com/en/1.6/ref/models/fields.

Administration

Views

Basic

In views.py file (application folder) you can add your code for your views.
This is the simplest view possible:

from django.http import HttpResponse
def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

To make use of this code it's required to map it to an url in the application and in the project. To map views with url's in the application it's required to create a file urls.py in the application folder. Its content will be something like that:

from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
    url(r'^$', views.index, name='index')
)

To map views with url's in the project it's required to add an include() to the project/urls.py file. Something like that:

from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
    url(r'^polls/', include('polls.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

url() function

The url() function takes four arguments, two required: regex and view, and two optional: kwargs, and name. The regex is a regular expression to match the url, it does not take GET neither POST arguments. In a request to http://www.example.com/myapp/?page=3, the URLconf will also look for myapp/.
The view argument is the function which Django will call passing an HttpRequest object as the first argument and, if the regex uses arguments, also are passed. This is an example of this kind of arguments:

# views.py
def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
# urls.py :
urlpatterns = patterns('',
    # ex: /polls/
    url(r'^$', views.index, name='index'),
    # ex: /polls/5/
    url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
)

Calling /polls/34/ will make a call like this one: detail(request=<HttpRequest object>, poll_id='34'). The poll_id='34' part comes from (?P<poll_id>\d+). ?P<poll_id> defines the name that will be used to identify the matched pattern; and \d+ is a regular expression to match a sequence of digits.

Notes

Setting another settings file

You should indicate your settings files, probably you'll need an environtment variable, to do easily you could execute manage using it:

$ DJANGO_SETTINGS_MODULE=settings.dev python manage.py runserver -l info

Or adding it before the imports:

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.dev')
 
from common.testCase import MongoTestCase
import engines.css.models as model
...