Some condensed notes on the Django tutorial (Django 1.3) This is just a short self-reference (or maybe a 2-minute overview), not an actual tutorial.
Database
Create / update database
python manage.py syncdbModels
Models define how data is stored. Create a model by inheriting from django.db.models.Model
from django.db import models class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField() def __unicode__(self): return self.choice
App
An “app” is simply a directory with an __init__.py file and other python files. (An “app” is more commonly known in other languages as a “package”.)
The INSTALLED_APPS variable in settings.py tells Django which apps to use.
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'polls' )
Make sure your app directory is on your Python path.
Re-run python manage.py syncdb after making changes to the INSTALLED_APPS.
URLs
The variable urlpatterns tells Django which Python code to run (which view to use) based on the url path.
from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^polls/$', 'polls.views.index'), (r'^polls/(?P <poll_id>\d+)/$', 'polls.views.detail'), url(r'^admin/', include(admin.site.urls)), )
The ROOT_URLCONF variable in settings.py tells Django where to find the module-level variable urlpatterns. E.g. if urlpatterns is defined in mysite/urls.py, the settings.py file should have
ROOT_URLCONF = 'mysite.urls'View
The code used to generate a page is called a view. A view is a Python function which returns a web page. Example index() view in polls/views.py
from django.template import Context, loader from polls.models import Poll from django.http import HttpResponse def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] t = loader.get_template('polls/index.html') c = Context({ 'latest_poll_list': latest_poll_list, }) return HttpResponse(t.render(c))
The urlpatterns tells Django which view to use based on the url. For example, the urlpatterns line
(r'^polls/$', 'polls.views.index'),
tells Django that the url http://site.com/polls is created by the index() function in polls/views.py.
render_to_response is a common shortcut for creating views. Equivalent view using render_to_response
from django.shortcuts import render_to_response from polls.models import Poll def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
Often views need to respond to a request. Templates use the {% csrf_token %} to prevent “Cross Site Request Forgeries”, and the view uses a django.template.RequestContext
from django.template import RequestContext # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p}, context_instance=RequestContext(request))
Template
A Django template is a HTML skeleton with special Django tags which tell the Django view where to fill in data. Example template polls/index.html
{% if latest_poll_list %} <ul> {% for poll in latest_poll_list %} <li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %}
Admin Interface
Register apps with Django’s admin interface
from polls.models import Poll from django.contrib import admin class PollAdmin(admin.ModelAdmin): fields = ['pub_date', 'question'] admin.site.register(Poll, PollAdmin)
Generic Views
There’s generic views which means that you don’t have to write a view function; you use django.views.generic to generate a simple view.
from django.conf.urls.defaults import patterns, include, url from django.views.generic import DetailView, ListView from polls.models import Poll urlpatterns = patterns('', (r'^$', ListView.as_view( queryset=Poll.objects.order_by('-pub_date')[:5], context_object_name='latest_poll_list', template_name='polls/index.html')), (r'^(?P <pk>\d+)/$', DetailView.as_view( model=Poll, template_name='polls/detail.html')), url(r'^(?P <pk>\d+)/results/$', DetailView.as_view( model=Poll, template_name='polls/results.html'), name='poll_results'), (r'^(?P <poll_id>\d+)/vote/$', 'polls.views.vote'), )