Django
This is a cheat sheet for starting, configuring, and developing a Django server and projects. The documentation is somewhat focused on my personal setup, which uses Ubuntu Server 12.04. Some steps may require modification on other OSes. The current stable version of Django as of this writing is 1.6.2. I don't get too verbose here; for more in-depth information see the Django tutorial and general documentation.
Contents
- 1 Initial Configuration
- 2 Database API
- 3 Admin Site
- 4 Templates
- 5 Maintenance
Initial Configuration
Installing Django
- Download the latest stable tarball from the Download page.
- Extract it to any temporary location
cd
into the directory and runsudo python setup.py install
.
Django will be installed into dist-packages.
Starting a Django Project
A Django project is a set of configurations and applications for a site. Its location should not be within the DocumentRoot of your web server, but the web server user should have permissions on it. I use /opt/django/projects/
as my root for all Django projects. To start a new project:
sudo mkdir /opt/django/projects sudo chown user:www-data /opt/django/projects sudo chmod g+s /opt/django/projects cd /opt/django/projects django-admin.py startproject projectname
If your project is going to house one application, it might be a good idea to name the project something slightly different from what you plan on naming the application.
Basic Project Configuration
Database configuration is kept in your project's projectname/settings.py
file. If using the default SQLite database backend, make sure the directory in which the database file will live is readable and writable by the web server's user. Configure the initial database with python manage.py syncdb
.
Also be sure to set the TIME_ZONE
variable to a value appropriate to your location (e.g. 'America/Chicago').
Starting a New Application
From within the root directory of the project that will serve the application, run python manage.py startapp appname
.
Add the application to the INSTALLED_APPS
list in the project's settings.py.
Creating the Models
Models are the Python representation of your database structure. Each model is a subclass of the django.db.models.Model
class, and represents a database table. The model has a number of attributes that correspond to the columns of the database. Models are stored in the application's models.py file. This example results in two simple database tables, Poll and Choice:
from django.db import models class Poll(models.Model): def __unicode__(self): return self.question question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): def __unicode__(self): return self.choice_text poll = models.ForeignKey(Poll) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)
The __unicode__
method provides a nicer way to identify an object instance from the shell.
For more examples of common field (column) types (such as CharField and IntegerField in the above example), see the field types page.
Database API
Things to Do with Models
Create records
record = Poll(question="What's new?", pub_date=timezone.now()) record.save()
Get list of all records
Poll.objects.all()
Get filtered list of records
Use '__' in place of '.' in filter parameters. 'pk' is a shortcut for the primary key.
Poll.objects.filter(id=1) Poll.objects.filter(question__startswith="What")
Get a single record
Poll.objects.get(pk=1)
Things to Do with Records
Get the rowid
record.id
Get/set the fields
record.question = "What's up?" record.save()
Things to Do with Foreign Key Relationships
An attribute is added to the "parent" model that points to the record's "children". By default, the name is childmodelname_set
, but can be overridden by the related_name
argument to the ForeignKey field.
Get all children
parent.choice_set.all()
Create new child record
parent.choice_set.create(attr1='val1', attr2='val2', ...)
Count children
parent.choice_set.count()
Admin Site
Adding applications to the admin site
In an application's admin.py file, import the desired models and add them to the admin interface:
from django.contrib import admin from polls.models import Poll class PollAdmin(admin.ModelAdmin): # Set the display order of the fields here fields = ['pub_date', 'question'] admin.site.register(Poll, PollAdmin)
Grouping fields together
class PollAdmin(admin.ModelAdmin): fieldsets = [ # Group name Group fields (None, {'fields': ['question']}), ('Date information', {'fields': ['pub_date']}), ]
Starting fieldsets in collapsed state
class PollAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ]
Adding foreign key "children"
from django.contrib import admin from polls.models import Choice, Poll # Can also try admin.StackedInline class ChoiceInline(admin.TabularInline): model = Choice # Number of empties to start with extra = 3 class PollAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] admin.site.register(Poll, PollAdmin)
List View (Change List)
Adding information to the list view
class PollAdmin(admin.ModelAdmin): # ... list_display = ('question', 'pub_date', 'was_published_recently')
Improving display of boolean types
class Poll(models.Model): # ... def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) was_published_recently.admin_order_field = 'pub_date' was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?'
Filtering the list view
class PollAdmin(admin.ModelAdmin): # ... list_filter = ['pub_date']
Searching in the list view
class PollAdmin(admin.ModelAdmin): # ... search_fields = ['question']
Templates
Modifying a stock template
To edit a stock template, first configure a custom templates directory. Create the directory (for example, from your base project directory) and add the following to the project's settings.py:
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
Then copy the template from its source to the templates directory:
cp /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/base_site.html templates/admin/
Edit as desired.
Maintenance
Starting the Development Web Server
Django comes with a built-in web server that can be used for testing works-in-progress. It is run via the manage.py script in the project's root directory.
python manage.py runserver
By default, the server will accept connections only from localhost, and uses port 8000. To open it up to remote connections and change the port (e.g. to 8080):
python manage.py runserver 0.0.0.0:8080
Viewing the SQL Schema of the Database
python manage.py sql appname
Updating the Database
When models are added or modified, the database can be updated with:
python manage.py syncdb
Entering an Interactive Python Shell
To start an interactive Python shell with the environment set up for your Django project, use:
python manage.py shell