Code


Version 4 (modified by anonymous, 8 years ago) (diff)

--

Django Cheat Sheet

The django tutorials are quite good. The goal of this cheat sheet is to create a quick start guide so that after reading the tuts over once or twice you have a more handy reference. Things in this guide are done the 'right' way with generic views and templates right off the bat. Please please add to this page.

Starting a project…

django-admin.py startproject AcmeIntranet
cd AcmeIntranet
edit settings.py
  • edit your database settings
  • set path to media dir ( e.g. /home/joe/AcmeIntranet/media )
    • media contains public files such as css and js files
  • set path to template dir
    • templates contains django html templates
    • your applications will likely have their own template dirs. Remember to add those as you create them
python manage.py syncdb

Creating an application…

python manage.py startapp invoices

add 'AcmeIntranet.invoices', to INSTALLED_APPS list in settings.py

edit invoices/models.py

from django.db import models
from django.contrib.auth.models import User

class Ticket (models.Model):
  user = models.ForeignKey (User) 
  case_number = models.IntegerField()
  dollar_amount = models.FloatField('Cost (in dollars)', max_digits=10, decimal_places=2)

validate your model and and commit to database:

python manage.py validate
python manage.py sql invoices
python manage.py syncdb

urls

in the project root directory, edit urls.py:

(r'^invoices/', include('AcmeIntranet.invoices.urls')) 

in the invoices app directory create urls.py:

from django.conf.urls.defaults import *
from AcmeIntranet.invoices.models import Invoice

info_dict = {
  'queryset': Invoice.objects.all()
}

urlpatterns = patterns('',
    (r'^$', 'django.views.generic.list_detail.object_list', info_dict),
    (r'^new/$', 'django.views.generic.create_update.???', { 'model': Invoice } ),
    (r'^(?P<object_id>\d+)/$', 'django.views.generic.list_detail.object_detail', info_dict),
)