Basics of Django

Start a New Project

django-admin.py startproject [proj name]

Start a New App

cd into your project's directory and type:

python manage.py startapp [app name]

Configuring Django

At minimum you need to have the database settings in settings.py configured. If you're using python v2.5 or later, you can make things easy for yourself by using sqlite3 as the DATABASE_ENGINE for now. Then, simply select a DATABASE_NAME (like 'appData.db') and you're set.

Now you can run the server with:

python manage.py runserver

Start The Server

python manage.py runserver

Define a Model For Your Application

In the folder for your application, you'll find a file called 'models.py'. This is where you will define the models. Here's an example:

from django.db import models

# Create your models here.
class List(models.Model):
  name = models.CharField(max_length=128)

class ListItem(models.Model):
  parent = models.ForeignKey(List)
  date = models.DateTimeField('date added')
  priority = models.IntegerField()
  finished = models.BooleanField()  


Make sure you also add your app to the INSTALLED_APPS tuple in settings.py.
Here's a list of all the model field types in Django.

Common Model Fields
CharField(max_length=x)
DateTimeField()
IntegerField()
BooleanField()
DecimalField()
EmailField(max_length=x) # use for emails if you want address validation
TextField() # use for a lot of text
ManyToManyField([class name])
..and a lot of other interesting ones.

Adding a New Application To Your Project

Add the application as an entry in the INSTALLED_APPS tuple in settings.py. Most of the time, the application will be inside the folder for your project, so the entry will look something like:

'[project name].[app name]'

#example:
INSTALLED_APPS = ('todo.list')

Adding a View

Views in Django are just functions.

Step 1: Add a URL
URLs are added in urls.py. The basic format for a url is:
([regular expression],[function to call])

For example:
(r'^myapp', include('todo.myapp.views.index'))


This says that any urls that start with myapp will get their data via the index function. The index function resides in todo > myapp > views.py, where todo is the name of the project, and myapp is the name of the app.


Step 2: Writing the Function

There are two ways to write a function. If you want to just send back HTML, it's as easy as:

from django.http import HttpResponse
def index(request):
return HttpResponse("Here's some text.")


But this is not convenient for larger pages. Instead, we usually use templates. Here's an example:

from django.shortcuts import render_to_response
def index(request):
# format:render_to_response('[name of template]', [dictionary of values])
return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})


Check out the entry on templates for more.

Notice that both functions get one parameter: a request object.

Templates For Views

Step 1:
Make a directory to hold all your templates. Then, add the absolute path to this directory as an entry in the TEMPLATE_DIRS tuple in settings.py.

Step 2:
Create a subfolder for whatever app you are going to be making templates for.

Step 3:
Create the template. A template is just a normal HTML file, with some variables and template tags thrown in. For example, suppose in your view you have the following render_to_response function call:

mydata = "hello there!"
return render_to_response('myapp/index.html', {'test_data': mydata})


Here, the function will show the "index.html" template inside the myapp folder. We're also sending the template a string. If we want to just show this string in the template, "index.html" could be as simple as:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head></head>
<body>

{{test_data}}

</body>
</html>

The {{ }} means print the value to the screen.

Capturing Data Via a URL

Here's a URL pattern:
(r'^polls/(?Pd+)/$', 'mysite.polls.views.detail'),


It will capture urls like:
polls/13/
polls/510/
polls/63/

etc..

and send the number to the detail() function. You can use the number if the function like so:

def detail(request, poll_id):
  return HttpResponse("You are looking at poll number: " + poll_id)

Filtering QuerySets

Here's a quick example:

finished_items = ListItem.objects.all().order_by('priority').filter(finished=1)


The documentation is here.

Creating Simple Custom Tags

Suppose we want to define our own tag {% say_hello %} that just gets replaced with "hello". Here's how to do it:

Step 1
Create a folder called "templatetags" at the same level as models.py, views.py etc in your app. Add an empty file in it called "__init__.py" and then another file called "custom.py".

Step 2
Add this code to custom.py:

from django.template import Library
register = Library()

@register.simple_tag
def say_hello():
return "hello!"


We use a decorator to register the say_hello class as a simple tag. The say_hello class is pretty straightforward — it just returns "hello" to the template.

Step 3
To use this in a template, load the custom tags first:

{% load custom %} # remember, our file was called "custom"
{% say_hello %}



Functions with arguments

These are almost as easy. Let's say we want a function that squares a number. Here is the code for custom.py:

@register.simple_tag
def squarer(x):
  return x*x


And for the template:

{% load custom %}
{% squarer 5 %}

Optional Fields

To define a field as optional in a model, both 'blank' and 'null' must be set to True:

description = models.TextField(blank=True,null=True)

Writing a Custom Filter

A filter looks something like this:

from django.template import Library
register = Library()

# use if your filter returns a string
from django.template.defaultfilters import stringfilter

@register.filter_function # register the filter with the library
@stringfilter # use if it returns a string
def guess_name(value): # value is the thing to filter: {{[value]|[filter]}}
return value.replace("_", ' ')


Save the filter in some file in a folder called 'templatetags' in your app's folder. Don't forget to put an empty file called '__init__.py' in that folder too. Then, include the filter in the appropriate template. If you saved it in 'custom.py', include it using:


{% load custom %}

Uploading a File

Remember to set your form's enctype to multipart/form-data:
<form action="/upload/" method="POST" enctype="multipart/form-data">
<input type="file" />


In your model, use a FileField or ImageField as appropriate:

def Image(models.Model):
  image = models.ImageField(upload_to="uploaded")


When your file is uploaded, it will be in the special dictionary FILES which you can now use:

def upload(request):
  for f in request.FILES.keys():
    i = Image(image=request.FILES[f])
    i.save()

Adding Comments To a Django App

It's really quite easy. This example has everything you would need to know.