Django Tutorial I
  • Written by P. Jury
  • August 13th, 2014
  • About Django

Django Tutorial I

I understand that there are already a ton of tutorials on getting started in Django. I just wanted to write the one I would have liked to have. Python experience is a plus but as a much better programmer than me once told me, “You can be a great Django developer and a piss poor Python programmer".

Prerequisites:

  • Debian Linux (I will add package installation instructions for other operating systems late)
  • Internet Connection
  • Good text editor (Scite, Vim, Emacs, Sublime Text, Komodo Edit, etc.)
  • Basic Linux CLI proficiency

Virtualenv and Virtualenvwrapper:

http://imgur.com/kZcTmvi Virtualenv is a environment isolation bootstrap for Python projects. I will create isolated Python workspaces with their own site packages, settings, and Python executable. This allows you to work with different versions of packages or different dependencies without cluttering your global python installation.

Pip:

Python-pip is a package management script for Python. It provides a unified way to install python packages from PyPi. We will use it to install Virtualenv and from within a virtualenv it allows us to install python packages to our isolated environment.

shell sudo apt-get install python-pip

Use pip to install virtualenv and virtualenvwrapper.

sudo pip install virtualenv virtualenvwrapper

Add this line to the end of your .bashrc or .profile (both of these should be in your home directory).

source /usr/loca/bin/virtualenvwrapper.sh

Restart your terminal and you will have Virtualenv installed and virtualenvwrapper scripts added to your PATH.

Now create a new virtualenv to use for this project. We will be creating a simple music library system in our examples.

``` killface@TheAnnihilatrix:~$ mkvirtualenv musiclibrary New python executable in musiclibrary/bin/python Installing setuptools, pip...done.

```

Once your env has been created it will be activated for you. You know an env is active when your shell prompt begins with the env name in parentheses. Like this: (musiclibrary)killface@TheAnnihilatrix:~$

That’s about all we need to know about Virtualenv for now. Just remember that when you are installing modules with pip, that we need to make sure the virtualenv for our project is active.

Installing Django 1.5 or,

It’s the version I picked... wanna fight about it?

If you still have your terminal open from the previous section, your virtualenv is still active (you will still see the environment name at the beginning of your shell prompt). If not, we need to activate the env like this:

killface@TheAnnihilatrix:~$ workon musiclibrary (musiclibrary)killface@TheAnnihilatrix:~$

Install Django.

pip install django==1.5

And that’s it.

Start our project

Django includes several scripts to generate our boilerplate code. To start a project. Create a repository root folder and change to that directory.

mkdir musiclibrary_project && cd musiclibrary_project

Let Django do the bitch work.

django-admin.py startproject musiclibrary

Your folder structure will now look like this:

musiclibrary_project/ |----musiclibrary/ |----manage.py |----musiclibrary/ |----__init__.py |----settings.py |----urls.py |----wsgi.py

We can now start the development server and take a look. python manage.py runserver

Browse to localhost:8000

Imgur Next up: Actually write some code! Or at least some configuration.

Environment Settings

Let’s open up our settings.py (musiclibrary/musiclibrary/settings.py).

```python

Django settings for musiclibrary project.

DEBUG = True TEMPLATE_DEBUG = DEBUG

ADMINS = ( # (’Your Name’, ’your_email@example.com’), )

MANAGERS = ADMINS

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. } }

Hosts/domain names that are valid for this site; required if DEBUG is False

See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts

ALLOWED_HOSTS = []

Local time zone for this installation. Choices can be found here:

http://en.wikipedia.org/wiki/Listoftzzonesby_name

although not all choices may be available on all operating systems.

In a Windows environment this must be set to your system time zone.

TIME_ZONE = ’America/Chicago’

Language code for this installation. All choices can be found here:

http://www.i18nguy.com/unicode/language-identifiers.html

LANGUAGE_CODE = ’en-us’

SITE_ID = 1

If you set this to False, Django will make some optimizations so as not

to load the internationalization machinery.

USE_I18N = True

If you set this to False, Django will not format dates, numbers and

calendars according to the current locale.

USE_L10N = True

If you set this to False, Django will not use timezone-aware datetimes.

USE_TZ = True

Absolute filesystem path to the directory that will hold user-uploaded files.

Example: “/var/www/example.com/media/"

MEDIA_ROOT = ’’

URL that handles the media served from MEDIA_ROOT. Make sure to use a

trailing slash.

Examples: “http://example.com/media/", “http://media.example.com/"

MEDIA_URL = ’’

Absolute path to the directory static files should be collected to.

Don’t put anything in this directory yourself; store your static files

in apps’ “static/” subdirectories and in STATICFILES_DIRS.

Example: “/var/www/example.com/static/"

STATIC_ROOT = ’’

URL prefix for static files.

Example: “http://example.com/static/", “http://static.example.com/"

STATIC_URL = ’/static/’

Additional locations of static files

STATICFILES_DIRS = ( # Put strings here, like “/home/html/static” or “C:/www/django/static". # Always use forward slashes, even on Windows. # Don’t forget to use absolute paths, not relative paths. )

List of finder classes that know how to find static files in

various locations.

STATICFILES_FINDERS = ( ’django.contrib.staticfiles.finders.FileSystemFinder’, ’django.contrib.staticfiles.finders.AppDirectoriesFinder’,

’django.contrib.staticfiles.finders.DefaultStorageFinder’,

)

Make this unique, and don’t share it with anybody.

SECRET_KEY = ’2h6gry!+0vd59^h*t1p-tlo9wa20y=x+b+azc#%pt#8-*ui-vz’

List of callables that know how to import templates from various sources.

TEMPLATELOADERS = ( ’django.template.loaders.filesystem.Loader’, ’django.template.loaders.appdirectories.Loader’,

’django.template.loaders.eggs.Loader’,

)

MIDDLEWARE_CLASSES = ( ’django.middleware.common.CommonMiddleware’, ’django.contrib.sessions.middleware.SessionMiddleware’, ’django.middleware.csrf.CsrfViewMiddleware’, ’django.contrib.auth.middleware.AuthenticationMiddleware’, ’django.contrib.messages.middleware.MessageMiddleware’, # Uncomment the next line for simple clickjacking protection: # ’django.middleware.clickjacking.XFrameOptionsMiddleware’, )

ROOT_URLCONF = ’musiclibrary.urls’

Python dotted path to the WSGI application used by Django’s runserver.

WSGI_APPLICATION = ’musiclibrary.wsgi.application’

TEMPLATEDIRS = ( # Put strings here, like “/home/html/djangotemplates” or “C:/www/django/templates". # Always use forward slashes, even on Windows. # Don’t forget to use absolute paths, not relative paths. )

INSTALLED_APPS = ( ’django.contrib.auth’, ’django.contrib.contenttypes’, ’django.contrib.sessions’, ’django.contrib.sites’, ’django.contrib.messages’, ’django.contrib.staticfiles’, # Uncomment the next line to enable the admin: # ’django.contrib.admin’, # Uncomment the next line to enable admin documentation: # ’django.contrib.admindocs’, )

A sample logging configuration. The only tangible logging

performed by this configuration is to send an email to

the site admins on every HTTP 500 error when DEBUG=False.

See http://docs.djangoproject.com/en/dev/topics/logging for

more details on how to customize your logging configuration.

LOGGING = { ’version’: 1, ’disableexistingloggers’: False, ’filters’: { ’requiredebugfalse’: { ’()’: ’django.utils.log.RequireDebugFalse’ } }, ’handlers’: { ’mailadmins’: { ’level’: ’ERROR’, ’filters’: [’requiredebugfalse’], ’class’: ’django.utils.log.AdminEmailHandler’ } }, ’loggers’: { ’django.request’: { ’handlers’: [’mailadmins’], ’level’: ’ERROR’, ’propagate’: True, }, } } ```

TL;DR: A whole buttload of values that make the thing do the thing.

We’ll start with our database settings. For our purposes we are going to use Sqlite3 as it is built in and requires next to zero extra configuration.

in our settings.py complete the value assignment for ENGINE.

```python DATABASES = { ’default’: { ###SET THIS VALUE### ’ENGINE’: ’django.db.backends.’, # Add ’postgresql_psycopg2’, ’mysql’, ’sqlite3’ or ’oracle’. ###THE ONE ABOVE ME### ’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. } }

```

While we’re editing the settings, lets start to enable Django’s awesome, built in backend admin pages.

In settings.py:

python INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: 'django.contrib.admindocs', ) Do what the comments say, uncomment ’django.contrib.admin’ and ’django.contrib.admindocs’.

Now lets edit our urls.py.

```python from django.conf.urls import patterns, include, url

Uncomment the next two lines to enable the admin:

from django.contrib import admin admin.autodiscover()

urlpatterns = patterns(’’, # Examples: # url(r’^$’, ’musiclibrary.views.home’, name=’home’), # url(r’^musiclibrary/’, include(’musiclibrary.foo.urls’)),

# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),

) ```

Again, do what the comments say to do.

Now we run: python manage.py syncdb We should see some tables get created, after that follow the prompt to create and admin user. ``` Creating tables ... Creating table authpermission Creating table authgrouppermissions Creating table authgroup Creating table authusergroups Creating table authuseruserpermissions Creating table authuser Creating table djangocontenttype Creating table djangosession Creating table djangosite Creating table djangoadminlog

You just installed Django’s auth system, which means you don’t have any superusers defined. Would you like to create one now? (yes/no): yes Username (leave blank to use ’killface’): Email address: killface@nevergoingbacktoAZ.net Password: Password (again): Superuser created successfully. Installing custom SQL ... Installing indexes ... Installed 0 object(s) from 0 fixture(s) ``` Now if we browse to localhost:8000/admin we should get prompted to login with the user account we created during our syncdb.

login

Not much to do in there yet. We still need to add some application code and display templates and models... we’ll start there in the next installment.

Welcome to Dropplets
Hey There!
What is This?