Fixed #4764 -- Added reference to Locale middleware in middleware docs. Thanks, dan...
[django.git] / docs / tutorial01.txt
blob180e30292d997ae8ae1212f030d4cbcc173f3c40
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
8 poll application.
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
18 installed.
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`` and we'll
26     try to help.
28 .. _django-users: http://groups.google.com/group/django-users
29 .. _#django: irc://irc.freenode.net/django
31 Creating a project
32 ==================
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 .. note::
46     You'll need to avoid naming projects after built-in Python or Django
47     components. In particular, this means you should avoid using names like
48     ``django`` (which will conflict with Django itself) or ``site`` (which
49     conflicts with a built-in Python package).
51 (``django-admin.py`` should be on your system path if you installed Django via
52 ``python setup.py``. If it's not on your path, you can find it in
53 ``site-packages/django/bin``, where ``site-packages`` is a directory within
54 your Python installation. Consider symlinking to ``django-admin.py`` from some
55 place on your path, such as ``/usr/local/bin``.)
57 .. admonition:: Where should this code live?
59     If your background is in PHP, you're probably used to putting code under the
60     Web server's document root (in a place such as ``/var/www``). With Django,
61     you don't do that. It's not a good idea to put any of this Python code within
62     your Web server's document root, because it risks the possibility that
63     people may be able to view your code over the Web. That's not good for
64     security.
66     Put your code in some directory **outside** of the document root, such as
67     ``/home/mycode``.
69 Let's look at what ``startproject`` created::
71     mysite/
72         __init__.py
73         manage.py
74         settings.py
75         urls.py
77 These files are:
79     * ``__init__.py``: An empty file that tells Python that this directory
80       should be considered a Python package. (Read `more about packages`_ in the
81       official Python docs if you're a Python beginner.)
82     * ``manage.py``: A command-line utility that lets you interact with this
83       Django project in various ways.
84     * ``settings.py``: Settings/configuration for this Django project.
85     * ``urls.py``: The URL declarations for this Django project; a "table of
86       contents" of your Django-powered site.
88 .. _more about packages: http://docs.python.org/tut/node8.html#packages
90 The development server
91 ----------------------
93 Let's verify this worked. Change into the ``mysite`` directory, if you
94 haven't already, and run the command ``python manage.py runserver``. You'll see
95 the following output on the command line::
97     Validating models...
98     0 errors found.
100     Django version 0.95, using settings 'mysite.settings'
101     Development server is running at http://127.0.0.1:8000/
102     Quit the server with CONTROL-C (Unix) or CTRL-BREAK (Windows).
104 You've started the Django development server, a lightweight Web server written
105 purely in Python. We've included this with Django so you can develop things
106 rapidly, without having to deal with configuring a production server -- such as
107 Apache -- until you're ready for production.
109 Now's a good time to note: DON'T use this server in anything resembling a
110 production environment. It's intended only for use while developing. (We're in
111 the business of making Web frameworks, not Web servers.)
113 Now that the server's running, visit http://127.0.0.1:8000/ with your Web
114 browser. You'll see a "Welcome to Django" page, in pleasant, light-blue pastel.
115 It worked!
117 .. admonition:: Changing the port
119     By default, the ``runserver`` command starts the development server on port
120     8000. If you want to change the server's port, pass it as a command-line
121     argument. For instance, this command starts the server on port 8080::
123         python manage.py runserver 8080
125     Full docs for the development server are at `django-admin documentation`_.
127 .. _django-admin documentation: ../django-admin/
129 Database setup
130 --------------
132 Now, edit ``settings.py``. It's a normal Python module with module-level
133 variables representing Django settings. Change these settings to match your
134 database's connection parameters:
136     * ``DATABASE_ENGINE`` -- Either 'postgresql_psycopg2', 'mysql' or 'sqlite3'.
137       Other backends are `also available`_.
138     * ``DATABASE_NAME`` -- The name of your database, or the full (absolute)
139       path to the database file if you're using SQLite.
140     * ``DATABASE_USER`` -- Your database username (not used for SQLite).
141     * ``DATABASE_PASSWORD`` -- Your database password (not used for SQLite).
142     * ``DATABASE_HOST`` -- The host your database is on. Leave this as an
143       empty string if your database server is on the same physical machine
144       (not used for SQLite).
146 .. _also available: ../settings/
148 .. admonition:: Note
150     If you're using PostgreSQL or MySQL, make sure you've created a database by
151     this point. Do that with "``CREATE DATABASE database_name;``" within your
152     database's interactive prompt.
154 While you're editing ``settings.py``, take note of the ``INSTALLED_APPS``
155 setting towards the bottom of the file. That variable holds the names of all
156 Django applications that are activated in this Django instance. Apps can be
157 used in multiple projects, and you can package and distribute them for use
158 by others in their projects.
160 By default, ``INSTALLED_APPS`` contains the following apps, all of which come
161 with Django:
163     * ``django.contrib.auth`` -- An authentication system.
164     * ``django.contrib.contenttypes`` -- A framework for content types.
165     * ``django.contrib.sessions`` -- A session framework.
166     * ``django.contrib.sites`` -- A framework for managing multiple sites
167       with one Django installation.
169 These applications are included by default as a convenience for the common
170 case.
172 Each of these applications makes use of at least one database table, though,
173 so we need to create the tables in the database before we can use them. To do
174 that, run the following command::
176     python manage.py syncdb
178 The ``syncdb`` command looks at the ``INSTALLED_APPS`` setting and creates any
179 necessary database tables according to the database settings in your
180 ``settings.py`` file. You'll see a message for each database table it creates,
181 and you'll get a prompt asking you if you'd like to create a superuser account
182 for the authentication system. Go ahead and do that.
184 If you're interested, run the command-line client for your database and type
185 ``\dt`` (PostgreSQL), ``SHOW TABLES;`` (MySQL), or ``.schema`` (SQLite) to
186 display the tables Django created.
188 .. admonition:: For the minimalists
190     Like we said above, the default applications are included for the common
191     case, but not everybody needs them. If you don't need any or all of them,
192     feel free to comment-out or delete the appropriate line(s) from
193     ``INSTALLED_APPS`` before running ``syncdb``. The ``syncdb`` command will
194     only create tables for apps in ``INSTALLED_APPS``.
196 Creating models
197 ===============
199 Now that your environment -- a "project" -- is set up, you're set to start
200 doing work.
202 Each application you write in Django consists of a Python package, somewhere
203 on your `Python path`_, that follows a certain convention. Django comes with a
204 utility that automatically generates the basic directory structure of an app,
205 so you can focus on writing code rather than creating directories.
207 .. admonition:: Projects vs. apps
209     What's the difference between a project and an app? An app is a Web
210     application that does something -- e.g., a weblog system, a database of
211     public records or a simple poll app. A project is a collection of
212     configuration and apps for a particular Web site. A project can contain
213     multiple apps. An app can be in multiple projects.
215 In this tutorial, we'll create our poll app in the ``mysite`` directory,
216 for simplicity. As a consequence, the app will be coupled to the project --
217 that is, Python code within the poll app will refer to ``mysite.polls``.
218 Later in this tutorial, we'll discuss decoupling your apps for distribution.
220 To create your app, make sure you're in the ``mysite`` directory and type
221 this command::
223     python manage.py startapp polls
225 That'll create a directory ``polls``, which is laid out like this::
227     polls/
228         __init__.py
229         models.py
230         views.py
232 This directory structure will house the poll application.
234 The first step in writing a database Web app in Django is to define your models
235 -- essentially, your database layout, with additional metadata.
237 .. admonition:: Philosophy
239    A model is the single, definitive source of data about your
240    data. It contains the essential fields and behaviors of the data you're
241    storing. Django follows the `DRY Principle`_. The goal is to define your
242    data model in one place and automatically derive things from it.
244 In our simple poll app, we'll create two models: polls and choices. A poll has
245 a question and a publication date. A choice has two fields: the text of the
246 choice and a vote tally. Each choice is associated with a poll.
248 These concepts are represented by simple Python classes. Edit the
249 ``polls/models.py`` file so it looks like this::
251     from django.db import models
253     class Poll(models.Model):
254         question = models.CharField(maxlength=200)
255         pub_date = models.DateTimeField('date published')
257     class Choice(models.Model):
258         poll = models.ForeignKey(Poll)
259         choice = models.CharField(maxlength=200)
260         votes = models.IntegerField()
262 The code is straightforward. Each model is represented by a class that
263 subclasses ``django.db.models.Model``. Each model has a number of class
264 variables, each of which represents a database field in the model.
266 Each field is represented by an instance of a ``models.*Field`` class -- e.g.,
267 ``models.CharField`` for character fields and ``models.DateTimeField`` for
268 datetimes. This tells Django what type of data each field holds.
270 The name of each ``models.*Field`` instance (e.g. ``question`` or ``pub_date`` )
271 is the field's name, in machine-friendly format. You'll use this value in your
272 Python code, and your database will use it as the column name.
274 You can use an optional first positional argument to a ``Field`` to designate a
275 human-readable name. That's used in a couple of introspective parts of Django,
276 and it doubles as documentation. If this field isn't provided, Django will use
277 the machine-readable name. In this example, we've only defined a human-readable
278 name for ``Poll.pub_date``. For all other fields in this model, the field's
279 machine-readable name will suffice as its human-readable name.
281 Some ``Field`` classes have required elements. ``CharField``, for example,
282 requires that you give it a ``maxlength``. That's used not only in the database
283 schema, but in validation, as we'll soon see.
285 Finally, note a relationship is defined, using ``models.ForeignKey``. That tells
286 Django each Choice is related to a single Poll. Django supports all the common
287 database relationships: many-to-ones, many-to-manys and one-to-ones.
289 .. _`Python path`: http://docs.python.org/tut/node8.html#SECTION008110000000000000000
290 .. _DRY Principle: http://c2.com/cgi/wiki?DontRepeatYourself
292 Activating models
293 =================
295 That small bit of model code gives Django a lot of information. With it, Django
296 is able to:
298     * Create a database schema (``CREATE TABLE`` statements) for this app.
299     * Create a Python database-access API for accessing Poll and Choice objects.
301 But first we need to tell our project that the ``polls`` app is installed.
303 .. admonition:: Philosophy
305     Django apps are "pluggable": You can use an app in multiple projects, and
306     you can distribute apps, because they don't have to be tied to a given
307     Django installation.
309 Edit the ``settings.py`` file again, and change the ``INSTALLED_APPS`` setting
310 to include the string ``'mysite.polls'``. So it'll look like this::
312     INSTALLED_APPS = (
313         'django.contrib.auth',
314         'django.contrib.contenttypes',
315         'django.contrib.sessions',
316         'django.contrib.sites',
317         'mysite.polls'
318     )
320 Now Django knows ``mysite`` includes the ``polls`` app. Let's run another command::
322     python manage.py sql polls
324 You should see something similar to the following (the CREATE TABLE SQL statements
325 for the polls app)::
327     BEGIN;
328     CREATE TABLE "polls_poll" (
329         "id" serial NOT NULL PRIMARY KEY,
330         "question" varchar(200) NOT NULL,
331         "pub_date" timestamp with time zone NOT NULL
332     );
333     CREATE TABLE "polls_choice" (
334         "id" serial NOT NULL PRIMARY KEY,
335         "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id"),
336         "choice" varchar(200) NOT NULL,
337         "votes" integer NOT NULL
338     );
339     COMMIT;
341 Note the following:
343     * The exact output will vary depending on the database you are using.
345     * Table names are automatically generated by combining the name of the app
346       (``polls``) and the lowercase name of the model -- ``poll`` and
347       ``choice``. (You can override this behavior.)
349     * Primary keys (IDs) are added automatically. (You can override this, too.)
351     * By convention, Django appends ``"_id"`` to the foreign key field name.
352       Yes, you can override this, as well.
354     * The foreign key relationship is made explicit by a ``REFERENCES`` statement.
356     * It's tailored to the database you're using, so database-specific field
357       types such as ``auto_increment`` (MySQL), ``serial`` (PostgreSQL), or
358       ``integer primary key`` (SQLite) are handled for you automatically. Same
359       goes for quoting of field names -- e.g., using double quotes or single
360       quotes. The author of this tutorial runs PostgreSQL, so the example
361       output is in PostgreSQL syntax.
363     * The ``sql`` command doesn't actually run the SQL in your database - it just
364       prints it to the screen so that you can see what SQL Django thinks is required.
365       If you wanted to, you could copy and paste this SQL into your database prompt.
366       However, as we will see shortly, Django provides an easier way of committing
367       the SQL to the database.
369 If you're interested, also run the following commands:
370     * ``python manage.py validate polls`` -- Checks for any errors in the
371       construction of your models.
373     * ``python manage.py sqlcustom polls`` -- Outputs any custom SQL statements
374       (such as table modifications or constraints) that are defined for the
375       application.
377     * ``python manage.py sqlclear polls`` -- Outputs the necessary ``DROP
378       TABLE`` statements for this app, according to which tables already exist
379       in your database (if any).
381     * ``python manage.py sqlindexes polls`` -- Outputs the ``CREATE INDEX``
382       statements for this app.
384     * ``python manage.py sqlall polls`` -- A combination of all the SQL from
385       the 'sql', 'sqlcustom', and 'sqlindexes' commands.
387 Looking at the output of those commands can help you understand what's actually
388 happening under the hood.
390 Now, run ``syncdb`` again to create those model tables in your database::
392     python manage.py syncdb
394 The ``syncdb`` command runs the sql from 'sqlall' on your database for all apps
395 in ``INSTALLED_APPS`` that don't already exist in your database. This creates
396 all the tables, initial data and indexes for any apps you have added to your
397 project since the last time you ran syncdb. ``syncdb`` can be called as often
398 as you like, and it will only ever create the tables that don't exist.
400 Read the `django-admin.py documentation`_ for full information on what the
401 ``manage.py`` utility can do.
403 .. _django-admin.py documentation: ../django-admin/
405 Playing with the API
406 ====================
408 Now, let's hop into the interactive Python shell and play around with the free
409 API Django gives you. To invoke the Python shell, use this command::
411     python manage.py shell
413 We're using this instead of simply typing "python", because ``manage.py`` sets
414 up the project's environment for you. "Setting up the environment" involves two
415 things:
417     * Putting ``mysite`` on ``sys.path``. For flexibility, several pieces of
418       Django refer to projects in Python dotted-path notation (e.g.
419       ``'mysite.polls.models'``). In order for this to work, the
420       ``mysite`` package has to be on ``sys.path``.
422       We've already seen one example of this: the ``INSTALLED_APPS`` setting is
423       a list of packages in dotted-path notation.
425     * Setting the ``DJANGO_SETTINGS_MODULE`` environment variable, which gives
426       Django the path to your ``settings.py`` file.
428 .. admonition:: Bypassing manage.py
430     If you'd rather not use ``manage.py``, no problem. Just make sure
431     ``mysite`` is at the root level on the Python path (i.e.,
432     ``import mysite`` works) and set the ``DJANGO_SETTINGS_MODULE``
433     environment variable to ``mysite.settings``.
435     For more information on all of this, see the `django-admin.py documentation`_.
437 Once you're in the shell, explore the database API::
439     # Import the model classes we just wrote.
440     >>> from mysite.polls.models import Poll, Choice
442     # No polls are in the system yet.
443     >>> Poll.objects.all()
444     []
446     # Create a new Poll.
447     >>> from datetime import datetime
448     >>> p = Poll(question="What's up?", pub_date=datetime.now())
450     # Save the object into the database. You have to call save() explicitly.
451     >>> p.save()
453     # Now it has an ID. Note that this might say "1L" instead of "1", depending
454     # on which database you're using. That's no biggie; it just means your
455     # database backend prefers to return integers as Python long integer
456     # objects.
457     >>> p.id
458     1
460     # Access database columns via Python attributes.
461     >>> p.question
462     "What's up?"
463     >>> p.pub_date
464     datetime.datetime(2005, 7, 15, 12, 00, 53)
466     # Change values by changing the attributes, then calling save().
467     >>> p.pub_date = datetime(2005, 4, 1, 0, 0)
468     >>> p.save()
470     # objects.all() displays all the polls in the database.
471     >>> Poll.objects.all()
472     [<Poll: Poll object>]
475 Wait a minute. ``<Poll: Poll object>`` is, utterly, an unhelpful
476 representation of this object. Let's fix that by editing the polls model (in
477 the ``polls/models.py`` file) and adding a ``__unicode__()`` method to both
478 ``Poll`` and ``Choice``::
480     class Poll(models.Model):
481         # ...
482         def __unicode__(self):
483             return self.question
485     class Choice(models.Model):
486         # ...
487         def __unicode__(self):
488             return self.choice
490 It's important to add ``__unicode__()`` methods to your models, not only for
491 your own sanity when dealing with the interactive prompt, but also because
492 objects' representations are used throughout Django's automatically-generated
493 admin.
495 .. admonition:: Why ``__unicode__()`` and not ``__str__()``?
497     If you're familiar with Python, you might be in the habit of adding
498     ``__str__()`` methods to your classes, not ``__unicode__()`` methods.
499     We use ``__unicode__()`` here because Django models deal with Unicode by
500     default. All data stored in your database is converted to Unicode when it's
501     returned.
503     Django models have a default ``__str__()`` method that calls
504     ``__unicode__()`` and converts the result to a UTF-8 bytestring. This means
505     that ``unicode(p)`` will return a Unicode string, and ``str(p)`` will return
506     a normal string, with characters encoded as UTF-8.
508     If all of this is jibberish to you, just remember to add ``__unicode__()``
509     methods to your models. With any luck, things should Just Work for you.
511 Note these are normal Python methods. Let's add a custom method, just for
512 demonstration::
514     import datetime
515     # ...
516     class Poll(models.Model):
517         # ...
518         def was_published_today(self):
519             return self.pub_date.date() == datetime.date.today()
521 Note the addition of ``import datetime`` to reference Python's standard
522 ``datetime`` module.
524 Let's jump back into the Python interactive shell by running
525 ``python manage.py shell`` again::
527     >>> from mysite.polls.models import Poll, Choice
529     # Make sure our __unicode__() addition worked.
530     >>> Poll.objects.all()
531     [<Poll: What's up?>]
533     # Django provides a rich database lookup API that's entirely driven by
534     # keyword arguments.
535     >>> Poll.objects.filter(id=1)
536     [<Poll: What's up?>]
537     >>> Poll.objects.filter(question__startswith='What')
538     [<Poll: What's up?>]
540     # Get the poll whose year is 2005. Of course, if you're going through this
541     # tutorial in another year, change as appropriate.
542     >>> Poll.objects.get(pub_date__year=2005)
543     <Poll: What's up?>
545     >>> Poll.objects.get(id=2)
546     Traceback (most recent call last):
547         ...
548     DoesNotExist: Poll matching query does not exist.
550     # Lookup by a primary key is the most common case, so Django provides a
551     # shortcut for primary-key exact lookups.
552     # The following is identical to Poll.objects.get(id=1).
553     >>> Poll.objects.get(pk=1)
554     <Poll: What's up?>
556     # Make sure our custom method worked.
557     >>> p = Poll.objects.get(pk=1)
558     >>> p.was_published_today()
559     False
561     # Give the Poll a couple of Choices. The create call constructs a new
562     # choice object, does the INSERT statement, adds the choice to the set
563     # of available choices and returns the new Choice object.
564     >>> p = Poll.objects.get(pk=1)
565     >>> p.choice_set.create(choice='Not much', votes=0)
566     <Choice: Not much>
567     >>> p.choice_set.create(choice='The sky', votes=0)
568     <Choice: The sky>
569     >>> c = p.choice_set.create(choice='Just hacking again', votes=0)
571     # Choice objects have API access to their related Poll objects.
572     >>> c.poll
573     <Poll: What's up?>
575     # And vice versa: Poll objects get access to Choice objects.
576     >>> p.choice_set.all()
577     [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
578     >>> p.choice_set.count()
579     3
581     # The API automatically follows relationships as far as you need.
582     # Use double underscores to separate relationships.
583     # This works as many levels deep as you want. There's no limit.
584     # Find all Choices for any poll whose pub_date is in 2005.
585     >>> Choice.objects.filter(poll__pub_date__year=2005)
586     [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
588     # Let's delete one of the choices. Use delete() for that.
589     >>> c = p.choice_set.filter(choice__startswith='Just hacking')
590     >>> c.delete()
592 For full details on the database API, see our `Database API reference`_.
594 When you're comfortable with the API, read `part 2 of this tutorial`_ to get
595 Django's automatic admin working.
597 .. _Database API reference: ../db-api/
598 .. _part 2 of this tutorial: ../tutorial02/