1 =====================================
2 Writing your first Django app, part 1
3 =====================================
5 Let's learn by example.
7 Throughout this tutorial, we'll walk you through the creation of a basic
10 It'll consist of two parts:
12 * A public site that lets people view polls and vote in them.
13 * An admin site that lets you add, change and delete polls.
15 We'll assume you have `Django installed`_ already. You can tell Django is
16 installed by running the Python interactive interpreter and typing
17 ``import django``. If that command runs successfully, with no errors, Django is
20 .. _`Django installed`: ../install/
22 .. admonition:: Where to get help:
24 If you're having trouble going through this tutorial, please post a message
25 to `django-users`_ or drop by `#django`_ on ``irc.freenode.net`` to chat
26 with other Django users who might be able to help.
28 .. _django-users: http://groups.google.com/group/django-users
29 .. _#django: irc://irc.freenode.net/django
34 If this is your first time using Django, you'll have to take care of some
35 initial setup. Namely, you'll need to auto-generate some code that establishes
36 a Django *project* -- a collection of settings for an instance of Django,
37 including database configuration, Django-specific options and
38 application-specific settings.
40 From the command line, ``cd`` into a directory where you'd like to store your
41 code, then run the command ``django-admin.py startproject mysite``. This
42 will create a ``mysite`` directory in your current directory.
44 .. admonition:: Mac OS X permissions
46 If you're using Mac OS X, you may see the message "permission
47 denied" when you try to run ``django-admin.py startproject``. This
48 is because, on Unix-based systems like OS X, a file must be marked
49 as "executable" before it can be run as a program. To do this, open
50 Terminal.app and navigate (using the ``cd`` command) to the directory
51 where ``django-admin.py`` is installed, then run the command
52 ``chmod +x django-admin.py``.
56 You'll need to avoid naming projects after built-in Python or Django
57 components. In particular, this means you should avoid using names like
58 ``django`` (which will conflict with Django itself) or ``site`` (which
59 conflicts with a built-in Python package).
61 (``django-admin.py`` should be on your system path if you installed Django via
62 ``python setup.py``. If it's not on your path, you can find it in
63 ``site-packages/django/bin``, where ``site-packages`` is a directory within
64 your Python installation. Consider symlinking to ``django-admin.py`` from some
65 place on your path, such as ``/usr/local/bin``.)
67 .. admonition:: Where should this code live?
69 If your background is in PHP, you're probably used to putting code under the
70 Web server's document root (in a place such as ``/var/www``). With Django,
71 you don't do that. It's not a good idea to put any of this Python code within
72 your Web server's document root, because it risks the possibility that
73 people may be able to view your code over the Web. That's not good for
76 Put your code in some directory **outside** of the document root, such as
79 Let's look at what ``startproject`` created::
89 * ``__init__.py``: An empty file that tells Python that this directory
90 should be considered a Python package. (Read `more about packages`_ in the
91 official Python docs if you're a Python beginner.)
92 * ``manage.py``: A command-line utility that lets you interact with this
93 Django project in various ways.
94 * ``settings.py``: Settings/configuration for this Django project.
95 * ``urls.py``: The URL declarations for this Django project; a "table of
96 contents" of your Django-powered site.
98 .. _more about packages: http://docs.python.org/tut/node8.html#packages
100 The development server
101 ----------------------
103 Let's verify this worked. Change into the ``mysite`` directory, if you
104 haven't already, and run the command ``python manage.py runserver``. You'll see
105 the following output on the command line::
110 Django version 0.95, using settings 'mysite.settings'
111 Development server is running at http://127.0.0.1:8000/
112 Quit the server with CONTROL-C (Unix) or CTRL-BREAK (Windows).
114 You've started the Django development server, a lightweight Web server written
115 purely in Python. We've included this with Django so you can develop things
116 rapidly, without having to deal with configuring a production server -- such as
117 Apache -- until you're ready for production.
119 Now's a good time to note: DON'T use this server in anything resembling a
120 production environment. It's intended only for use while developing. (We're in
121 the business of making Web frameworks, not Web servers.)
123 Now that the server's running, visit http://127.0.0.1:8000/ with your Web
124 browser. You'll see a "Welcome to Django" page, in pleasant, light-blue pastel.
127 .. admonition:: Changing the port
129 By default, the ``runserver`` command starts the development server on port
130 8000. If you want to change the server's port, pass it as a command-line
131 argument. For instance, this command starts the server on port 8080::
133 python manage.py runserver 8080
135 Full docs for the development server are at `django-admin documentation`_.
137 .. _django-admin documentation: ../django-admin/
142 Now, edit ``settings.py``. It's a normal Python module with module-level
143 variables representing Django settings. Change these settings to match your
144 database's connection parameters:
146 * ``DATABASE_ENGINE`` -- Either 'postgresql_psycopg2', 'mysql' or 'sqlite3'.
147 Other backends are `also available`_.
148 * ``DATABASE_NAME`` -- The name of your database, or the full (absolute)
149 path to the database file if you're using SQLite.
150 * ``DATABASE_USER`` -- Your database username (not used for SQLite).
151 * ``DATABASE_PASSWORD`` -- Your database password (not used for SQLite).
152 * ``DATABASE_HOST`` -- The host your database is on. Leave this as an
153 empty string if your database server is on the same physical machine
154 (not used for SQLite).
156 .. _also available: ../settings/
160 If you're using PostgreSQL or MySQL, make sure you've created a database by
161 this point. Do that with "``CREATE DATABASE database_name;``" within your
162 database's interactive prompt.
164 If you're using SQLite, you don't need to create anything beforehand - the
165 database file will be created automatically when it is needed.
167 While you're editing ``settings.py``, take note of the ``INSTALLED_APPS``
168 setting towards the bottom of the file. That variable holds the names of all
169 Django applications that are activated in this Django instance. Apps can be
170 used in multiple projects, and you can package and distribute them for use
171 by others in their projects.
173 By default, ``INSTALLED_APPS`` contains the following apps, all of which come
176 * ``django.contrib.auth`` -- An authentication system.
177 * ``django.contrib.contenttypes`` -- A framework for content types.
178 * ``django.contrib.sessions`` -- A session framework.
179 * ``django.contrib.sites`` -- A framework for managing multiple sites
180 with one Django installation.
182 These applications are included by default as a convenience for the common
185 Each of these applications makes use of at least one database table, though,
186 so we need to create the tables in the database before we can use them. To do
187 that, run the following command::
189 python manage.py syncdb
191 The ``syncdb`` command looks at the ``INSTALLED_APPS`` setting and creates any
192 necessary database tables according to the database settings in your
193 ``settings.py`` file. You'll see a message for each database table it creates,
194 and you'll get a prompt asking you if you'd like to create a superuser account
195 for the authentication system. Go ahead and do that.
197 If you're interested, run the command-line client for your database and type
198 ``\dt`` (PostgreSQL), ``SHOW TABLES;`` (MySQL), or ``.schema`` (SQLite) to
199 display the tables Django created.
201 .. admonition:: For the minimalists
203 Like we said above, the default applications are included for the common
204 case, but not everybody needs them. If you don't need any or all of them,
205 feel free to comment-out or delete the appropriate line(s) from
206 ``INSTALLED_APPS`` before running ``syncdb``. The ``syncdb`` command will
207 only create tables for apps in ``INSTALLED_APPS``.
212 Now that your environment -- a "project" -- is set up, you're set to start
215 Each application you write in Django consists of a Python package, somewhere
216 on your `Python path`_, that follows a certain convention. Django comes with a
217 utility that automatically generates the basic directory structure of an app,
218 so you can focus on writing code rather than creating directories.
220 .. admonition:: Projects vs. apps
222 What's the difference between a project and an app? An app is a Web
223 application that does something -- e.g., a weblog system, a database of
224 public records or a simple poll app. A project is a collection of
225 configuration and apps for a particular Web site. A project can contain
226 multiple apps. An app can be in multiple projects.
228 In this tutorial, we'll create our poll app in the ``mysite`` directory,
229 for simplicity. As a consequence, the app will be coupled to the project --
230 that is, Python code within the poll app will refer to ``mysite.polls``.
231 Later in this tutorial, we'll discuss decoupling your apps for distribution.
233 To create your app, make sure you're in the ``mysite`` directory and type
236 python manage.py startapp polls
238 That'll create a directory ``polls``, which is laid out like this::
245 This directory structure will house the poll application.
247 The first step in writing a database Web app in Django is to define your models
248 -- essentially, your database layout, with additional metadata.
250 .. admonition:: Philosophy
252 A model is the single, definitive source of data about your
253 data. It contains the essential fields and behaviors of the data you're
254 storing. Django follows the `DRY Principle`_. The goal is to define your
255 data model in one place and automatically derive things from it.
257 In our simple poll app, we'll create two models: polls and choices. A poll has
258 a question and a publication date. A choice has two fields: the text of the
259 choice and a vote tally. Each choice is associated with a poll.
261 These concepts are represented by simple Python classes. Edit the
262 ``polls/models.py`` file so it looks like this::
264 from django.db import models
266 class Poll(models.Model):
267 question = models.CharField(max_length=200)
268 pub_date = models.DateTimeField('date published')
270 class Choice(models.Model):
271 poll = models.ForeignKey(Poll)
272 choice = models.CharField(max_length=200)
273 votes = models.IntegerField()
275 .. admonition:: Errors about ``max_length``
277 If Django gives you an error message saying that ``max_length`` is
278 not a valid argument, you're most likely using an old version of
279 Django. (This version of the tutorial is written for the latest
280 development version of Django.) If you're using a Subversion checkout
281 of Django's development version (see `the installation docs`_ for
282 more information), you shouldn't have any problems.
284 If you want to stick with an older version of Django, you'll want to
285 switch to `the Django 0.96 tutorial`_, because this tutorial covers
286 several features that only exist in the Django development version.
288 .. _the installation docs: ../install/
289 .. _the Django 0.96 tutorial: ../0.96/tutorial01/
291 The code is straightforward. Each model is represented by a class that
292 subclasses ``django.db.models.Model``. Each model has a number of class
293 variables, each of which represents a database field in the model.
295 Each field is represented by an instance of a ``models.*Field`` class -- e.g.,
296 ``models.CharField`` for character fields and ``models.DateTimeField`` for
297 datetimes. This tells Django what type of data each field holds.
299 The name of each ``models.*Field`` instance (e.g. ``question`` or ``pub_date`` )
300 is the field's name, in machine-friendly format. You'll use this value in your
301 Python code, and your database will use it as the column name.
303 You can use an optional first positional argument to a ``Field`` to designate a
304 human-readable name. That's used in a couple of introspective parts of Django,
305 and it doubles as documentation. If this field isn't provided, Django will use
306 the machine-readable name. In this example, we've only defined a human-readable
307 name for ``Poll.pub_date``. For all other fields in this model, the field's
308 machine-readable name will suffice as its human-readable name.
310 Some ``Field`` classes have required elements. ``CharField``, for example,
311 requires that you give it a ``max_length``. That's used not only in the database
312 schema, but in validation, as we'll soon see.
314 Finally, note a relationship is defined, using ``models.ForeignKey``. That tells
315 Django each Choice is related to a single Poll. Django supports all the common
316 database relationships: many-to-ones, many-to-manys and one-to-ones.
318 .. _`Python path`: http://docs.python.org/tut/node8.html#SECTION008110000000000000000
319 .. _DRY Principle: http://c2.com/cgi/wiki?DontRepeatYourself
324 That small bit of model code gives Django a lot of information. With it, Django
327 * Create a database schema (``CREATE TABLE`` statements) for this app.
328 * Create a Python database-access API for accessing Poll and Choice objects.
330 But first we need to tell our project that the ``polls`` app is installed.
332 .. admonition:: Philosophy
334 Django apps are "pluggable": You can use an app in multiple projects, and
335 you can distribute apps, because they don't have to be tied to a given
338 Edit the ``settings.py`` file again, and change the ``INSTALLED_APPS`` setting
339 to include the string ``'mysite.polls'``. So it'll look like this::
342 'django.contrib.auth',
343 'django.contrib.contenttypes',
344 'django.contrib.sessions',
345 'django.contrib.sites',
349 Now Django knows ``mysite`` includes the ``polls`` app. Let's run another command::
351 python manage.py sql polls
353 You should see something similar to the following (the CREATE TABLE SQL statements
357 CREATE TABLE "polls_poll" (
358 "id" serial NOT NULL PRIMARY KEY,
359 "question" varchar(200) NOT NULL,
360 "pub_date" timestamp with time zone NOT NULL
362 CREATE TABLE "polls_choice" (
363 "id" serial NOT NULL PRIMARY KEY,
364 "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id"),
365 "choice" varchar(200) NOT NULL,
366 "votes" integer NOT NULL
372 * The exact output will vary depending on the database you are using.
374 * Table names are automatically generated by combining the name of the app
375 (``polls``) and the lowercase name of the model -- ``poll`` and
376 ``choice``. (You can override this behavior.)
378 * Primary keys (IDs) are added automatically. (You can override this, too.)
380 * By convention, Django appends ``"_id"`` to the foreign key field name.
381 Yes, you can override this, as well.
383 * The foreign key relationship is made explicit by a ``REFERENCES`` statement.
385 * It's tailored to the database you're using, so database-specific field
386 types such as ``auto_increment`` (MySQL), ``serial`` (PostgreSQL), or
387 ``integer primary key`` (SQLite) are handled for you automatically. Same
388 goes for quoting of field names -- e.g., using double quotes or single
389 quotes. The author of this tutorial runs PostgreSQL, so the example
390 output is in PostgreSQL syntax.
392 * The ``sql`` command doesn't actually run the SQL in your database - it just
393 prints it to the screen so that you can see what SQL Django thinks is required.
394 If you wanted to, you could copy and paste this SQL into your database prompt.
395 However, as we will see shortly, Django provides an easier way of committing
396 the SQL to the database.
398 If you're interested, also run the following commands:
399 * ``python manage.py validate`` -- Checks for any errors in the
400 construction of your models.
402 * ``python manage.py sqlcustom polls`` -- Outputs any custom SQL statements
403 (such as table modifications or constraints) that are defined for the
406 * ``python manage.py sqlclear polls`` -- Outputs the necessary ``DROP
407 TABLE`` statements for this app, according to which tables already exist
408 in your database (if any).
410 * ``python manage.py sqlindexes polls`` -- Outputs the ``CREATE INDEX``
411 statements for this app.
413 * ``python manage.py sqlall polls`` -- A combination of all the SQL from
414 the 'sql', 'sqlcustom', and 'sqlindexes' commands.
416 Looking at the output of those commands can help you understand what's actually
417 happening under the hood.
419 Now, run ``syncdb`` again to create those model tables in your database::
421 python manage.py syncdb
423 The ``syncdb`` command runs the sql from 'sqlall' on your database for all apps
424 in ``INSTALLED_APPS`` that don't already exist in your database. This creates
425 all the tables, initial data and indexes for any apps you have added to your
426 project since the last time you ran syncdb. ``syncdb`` can be called as often
427 as you like, and it will only ever create the tables that don't exist.
429 Read the `django-admin.py documentation`_ for full information on what the
430 ``manage.py`` utility can do.
432 .. _django-admin.py documentation: ../django-admin/
437 Now, let's hop into the interactive Python shell and play around with the free
438 API Django gives you. To invoke the Python shell, use this command::
440 python manage.py shell
442 We're using this instead of simply typing "python", because ``manage.py`` sets
443 up the project's environment for you. "Setting up the environment" involves two
446 * Putting ``mysite`` on ``sys.path``. For flexibility, several pieces of
447 Django refer to projects in Python dotted-path notation (e.g.
448 ``'mysite.polls.models'``). In order for this to work, the
449 ``mysite`` package has to be on ``sys.path``.
451 We've already seen one example of this: the ``INSTALLED_APPS`` setting is
452 a list of packages in dotted-path notation.
454 * Setting the ``DJANGO_SETTINGS_MODULE`` environment variable, which gives
455 Django the path to your ``settings.py`` file.
457 .. admonition:: Bypassing manage.py
459 If you'd rather not use ``manage.py``, no problem. Just make sure
460 ``mysite`` is at the root level on the Python path (i.e.,
461 ``import mysite`` works) and set the ``DJANGO_SETTINGS_MODULE``
462 environment variable to ``mysite.settings``.
464 For more information on all of this, see the `django-admin.py documentation`_.
466 Once you're in the shell, explore the database API::
468 # Import the model classes we just wrote.
469 >>> from mysite.polls.models import Poll, Choice
471 # No polls are in the system yet.
472 >>> Poll.objects.all()
477 >>> p = Poll(question="What's up?", pub_date=datetime.datetime.now())
479 # Save the object into the database. You have to call save() explicitly.
482 # Now it has an ID. Note that this might say "1L" instead of "1", depending
483 # on which database you're using. That's no biggie; it just means your
484 # database backend prefers to return integers as Python long integer
489 # Access database columns via Python attributes.
493 datetime.datetime(2007, 7, 15, 12, 00, 53)
495 # Change values by changing the attributes, then calling save().
496 >>> p.pub_date = datetime.datetime(2007, 4, 1, 0, 0)
499 # objects.all() displays all the polls in the database.
500 >>> Poll.objects.all()
501 [<Poll: Poll object>]
504 Wait a minute. ``<Poll: Poll object>`` is, utterly, an unhelpful
505 representation of this object. Let's fix that by editing the polls model (in
506 the ``polls/models.py`` file) and adding a ``__unicode__()`` method to both
507 ``Poll`` and ``Choice``::
509 class Poll(models.Model):
511 def __unicode__(self):
514 class Choice(models.Model):
516 def __unicode__(self):
519 .. admonition:: If ``__unicode__()`` doesn't seem to work
521 If you add the ``__unicode__()`` method to your models and don't
522 see any change in how they're represented, you're most likely using
523 an old version of Django. (This version of the tutorial is written
524 for the latest development version of Django.) If you're using a
525 Subversion checkout of of Django's development version (see `the
526 installation docs`_ for more information), you shouldn't have any
529 If you want to stick with an older version of Django, you'll want to
530 switch to `the Django 0.96 tutorial`_, because this tutorial covers
531 several features that only exist in the Django development version.
533 .. _the installation docs: ../install/
534 .. _the Django 0.96 tutorial: ../0.96/tutorial01/
536 It's important to add ``__unicode__()`` methods to your models, not only for
537 your own sanity when dealing with the interactive prompt, but also because
538 objects' representations are used throughout Django's automatically-generated
541 .. admonition:: Why ``__unicode__()`` and not ``__str__()``?
543 If you're familiar with Python, you might be in the habit of adding
544 ``__str__()`` methods to your classes, not ``__unicode__()`` methods.
545 We use ``__unicode__()`` here because Django models deal with Unicode by
546 default. All data stored in your database is converted to Unicode when it's
549 Django models have a default ``__str__()`` method that calls
550 ``__unicode__()`` and converts the result to a UTF-8 bytestring. This means
551 that ``unicode(p)`` will return a Unicode string, and ``str(p)`` will return
552 a normal string, with characters encoded as UTF-8.
554 If all of this is jibberish to you, just remember to add ``__unicode__()``
555 methods to your models. With any luck, things should Just Work for you.
557 Note these are normal Python methods. Let's add a custom method, just for
562 class Poll(models.Model):
564 def was_published_today(self):
565 return self.pub_date.date() == datetime.date.today()
567 Note the addition of ``import datetime`` to reference Python's standard
570 Let's jump back into the Python interactive shell by running
571 ``python manage.py shell`` again::
573 >>> from mysite.polls.models import Poll, Choice
575 # Make sure our __unicode__() addition worked.
576 >>> Poll.objects.all()
579 # Django provides a rich database lookup API that's entirely driven by
581 >>> Poll.objects.filter(id=1)
583 >>> Poll.objects.filter(question__startswith='What')
586 # Get the poll whose year is 2007. Of course, if you're going through this
587 # tutorial in another year, change as appropriate.
588 >>> Poll.objects.get(pub_date__year=2007)
591 >>> Poll.objects.get(id=2)
592 Traceback (most recent call last):
594 DoesNotExist: Poll matching query does not exist.
596 # Lookup by a primary key is the most common case, so Django provides a
597 # shortcut for primary-key exact lookups.
598 # The following is identical to Poll.objects.get(id=1).
599 >>> Poll.objects.get(pk=1)
602 # Make sure our custom method worked.
603 >>> p = Poll.objects.get(pk=1)
604 >>> p.was_published_today()
607 # Give the Poll a couple of Choices. The create call constructs a new
608 # choice object, does the INSERT statement, adds the choice to the set
609 # of available choices and returns the new Choice object.
610 >>> p = Poll.objects.get(pk=1)
611 >>> p.choice_set.create(choice='Not much', votes=0)
613 >>> p.choice_set.create(choice='The sky', votes=0)
615 >>> c = p.choice_set.create(choice='Just hacking again', votes=0)
617 # Choice objects have API access to their related Poll objects.
621 # And vice versa: Poll objects get access to Choice objects.
622 >>> p.choice_set.all()
623 [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
624 >>> p.choice_set.count()
627 # The API automatically follows relationships as far as you need.
628 # Use double underscores to separate relationships.
629 # This works as many levels deep as you want; there's no limit.
630 # Find all Choices for any poll whose pub_date is in 2007.
631 >>> Choice.objects.filter(poll__pub_date__year=2007)
632 [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
634 # Let's delete one of the choices. Use delete() for that.
635 >>> c = p.choice_set.filter(choice__startswith='Just hacking')
638 For full details on the database API, see our `Database API reference`_.
640 When you're comfortable with the API, read `part 2 of this tutorial`_ to get
641 Django's automatic admin working.
643 .. _Database API reference: ../db-api/
644 .. _part 2 of this tutorial: ../tutorial02/