tutorial01.txt 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. =====================================
  2. Writing your first Django app, part 1
  3. =====================================
  4. Let's learn by example.
  5. Throughout this tutorial, we'll walk you through the creation of a basic
  6. poll application.
  7. It'll consist of two parts:
  8. * A public site that lets people view polls and vote in them.
  9. * An admin site that lets you add, change and delete polls.
  10. We'll assume you have :doc:`Django installed </intro/install>` already. You can
  11. tell Django is installed by running the Python interactive interpreter and
  12. typing ``import django``. If that command runs successfully, with no errors,
  13. Django is installed.
  14. .. admonition:: Where to get help:
  15. If you're having trouble going through this tutorial, please post a message
  16. to `django-users`__ or drop by `#django on irc.freenode.net`__ to chat
  17. with other Django users who might be able to help.
  18. __ http://groups.google.com/group/django-users
  19. __ irc://irc.freenode.net/django
  20. Creating a project
  21. ==================
  22. If this is your first time using Django, you'll have to take care of some
  23. initial setup. Namely, you'll need to auto-generate some code that establishes a
  24. Django :term:`project` -- a collection of settings for an instance of Django,
  25. including database configuration, Django-specific options and
  26. application-specific settings.
  27. From the command line, ``cd`` into a directory where you'd like to store your
  28. code, then run the following command:
  29. .. code-block:: bash
  30. django-admin.py startproject mysite
  31. This will create a ``mysite`` directory in your current directory.
  32. .. admonition:: Script name may differ in distribution packages
  33. If you installed Django using a Linux distribution's package manager
  34. (e.g. apt-get or yum) ``django-admin.py`` may have been renamed to
  35. ``django-admin``. You may continue through this documentation by omitting
  36. ``.py`` from each command.
  37. .. admonition:: Mac OS X permissions
  38. If you're using Mac OS X, you may see the message "permission denied" when
  39. you try to run ``django-admin.py startproject``. This is because, on
  40. Unix-based systems like OS X, a file must be marked as "executable" before it
  41. can be run as a program. To do this, open Terminal.app and navigate (using
  42. the ``cd`` command) to the directory where :doc:`django-admin.py
  43. </ref/django-admin>` is installed, then run the command
  44. ``sudo chmod +x django-admin.py``.
  45. .. 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 ``test`` (which
  49. conflicts with a built-in Python package).
  50. :doc:`django-admin.py </ref/django-admin>` should be on your system path if you
  51. installed Django via ``python setup.py``. If it's not on your path, you can find
  52. it in ``site-packages/django/bin``, where ``site-packages`` is a directory
  53. within your Python installation. Consider symlinking to :doc:`django-admin.py
  54. </ref/django-admin>` from some place on your path, such as
  55. :file:`/usr/local/bin`.
  56. .. admonition:: Where should this code live?
  57. If your background is in PHP, you're probably used to putting code under the
  58. Web server's document root (in a place such as ``/var/www``). With Django,
  59. you don't do that. It's not a good idea to put any of this Python code
  60. within your Web server's document root, because it risks the possibility
  61. that people may be able to view your code over the Web. That's not good for
  62. security.
  63. Put your code in some directory **outside** of the document root, such as
  64. :file:`/home/mycode`.
  65. Let's look at what :djadmin:`startproject` created::
  66. mysite/
  67. manage.py
  68. mysite/
  69. __init__.py
  70. settings.py
  71. urls.py
  72. wsgi.py
  73. .. admonition:: Doesn't match what you see?
  74. The default project layout recently changed. If you're seeing a "flat"
  75. layout (with no inner :file:`mysite/` directory), you're probably using
  76. a version of Django that doesn't match this tutorial version. You'll
  77. want to either switch to the older tutorial or the newer Django version.
  78. These files are:
  79. * The outer :file:`mysite/` directory is just a container for your
  80. project. Its name doesn't matter to Django; you can rename it to anything
  81. you like.
  82. * :file:`manage.py`: A command-line utility that lets you interact with this
  83. Django project in various ways. You can read all the details about
  84. :file:`manage.py` in :doc:`/ref/django-admin`.
  85. * The inner :file:`mysite/` directory is the actual Python package for your
  86. project. Its name is the Python package name you'll need to use to import
  87. anything inside it (e.g. ``import mysite.settings``).
  88. * :file:`mysite/__init__.py`: An empty file that tells Python that this
  89. directory should be considered a Python package. (Read `more about
  90. packages`_ in the official Python docs if you're a Python beginner.)
  91. * :file:`mysite/settings.py`: Settings/configuration for this Django
  92. project. :doc:`/topics/settings` will tell you all about how settings
  93. work.
  94. * :file:`mysite/urls.py`: The URL declarations for this Django project; a
  95. "table of contents" of your Django-powered site. You can read more about
  96. URLs in :doc:`/topics/http/urls`.
  97. * :file:`mysite/wsgi.py`: An entry-point for WSGI-compatible webservers to
  98. serve your project. See :doc:`/howto/deployment/wsgi/index` for more details.
  99. .. _more about packages: http://docs.python.org/tutorial/modules.html#packages
  100. The development server
  101. ----------------------
  102. Let's verify this worked. Change into the outer :file:`mysite` directory, if
  103. you haven't already, and run the command ``python manage.py runserver``. You'll
  104. see the following output on the command line::
  105. Validating models...
  106. 0 errors found.
  107. Django version 1.4, using settings 'mysite.settings'
  108. Development server is running at http://127.0.0.1:8000/
  109. Quit the server with CONTROL-C.
  110. You've started the Django development server, a lightweight Web server written
  111. purely in Python. We've included this with Django so you can develop things
  112. rapidly, without having to deal with configuring a production server -- such as
  113. Apache -- until you're ready for production.
  114. Now's a good time to note: DON'T use this server in anything resembling a
  115. production environment. It's intended only for use while developing. (We're in
  116. the business of making Web frameworks, not Web servers.)
  117. Now that the server's running, visit http://127.0.0.1:8000/ with your Web
  118. browser. You'll see a "Welcome to Django" page, in pleasant, light-blue pastel.
  119. It worked!
  120. .. admonition:: Changing the port
  121. By default, the :djadmin:`runserver` command starts the development server
  122. on the internal IP at port 8000.
  123. If you want to change the server's port, pass
  124. it as a command-line argument. For instance, this command starts the server
  125. on port 8080:
  126. .. code-block:: bash
  127. python manage.py runserver 8080
  128. If you want to change the server's IP, pass it along with the port. So to
  129. listen on all public IPs (useful if you want to show off your work on other
  130. computers), use:
  131. .. code-block:: bash
  132. python manage.py runserver 0.0.0.0:8000
  133. Full docs for the development server can be found in the
  134. :djadmin:`runserver` reference.
  135. Database setup
  136. --------------
  137. Now, edit :file:`mysite/settings.py`. It's a normal Python module with
  138. module-level variables representing Django settings. Change the
  139. following keys in the :setting:`DATABASES` ``'default'`` item to match
  140. your database connection settings.
  141. * :setting:`ENGINE <DATABASE-ENGINE>` -- Either
  142. ``'django.db.backends.postgresql_psycopg2'``,
  143. ``'django.db.backends.mysql'``, ``'django.db.backends.sqlite3'`` or
  144. ``'django.db.backends.oracle'``. Other backends are :setting:`also available
  145. <DATABASE-ENGINE>`.
  146. * :setting:`NAME` -- The name of your database. If you're using
  147. SQLite, the database will be a file on your computer; in that
  148. case, :setting:`NAME` should be the full absolute path,
  149. including filename, of that file. If the file doesn't exist, it
  150. will automatically be created when you synchronize the database
  151. for the first time (see below).
  152. When specifying the path, always use forward slashes, even on
  153. Windows (e.g. ``C:/homes/user/mysite/sqlite3.db``).
  154. * :setting:`USER` -- Your database username (not used for SQLite).
  155. * :setting:`PASSWORD` -- Your database password (not used for
  156. SQLite).
  157. * :setting:`HOST` -- The host your database is on. Leave this as
  158. an empty string if your database server is on the same physical
  159. machine (not used for SQLite).
  160. If you're new to databases, we recommend simply using SQLite by setting
  161. :setting:`ENGINE` to ``'django.db.backends.sqlite3'`` and :setting:`NAME` to
  162. the place where you'd like to store the database. SQLite is included in Python,
  163. so you won't need to install anything else to support your database.
  164. .. note::
  165. If you're using PostgreSQL or MySQL, make sure you've created a database by
  166. this point. Do that with "``CREATE DATABASE database_name;``" within your
  167. database's interactive prompt.
  168. If you're using SQLite, you don't need to create anything beforehand - the
  169. database file will be created automatically when it is needed.
  170. While you're editing :file:`settings.py`, set :setting:`TIME_ZONE` to your
  171. time zone. The default value is the Central time zone in the U.S. (Chicago).
  172. Also, note the :setting:`INSTALLED_APPS` setting toward the bottom of
  173. the file. That holds the names of all Django applications that are
  174. activated in this Django instance. Apps can be used in multiple projects, and
  175. you can package and distribute them for use by others in their projects.
  176. By default, :setting:`INSTALLED_APPS` contains the following apps, all of which
  177. come with Django:
  178. * :mod:`django.contrib.auth` -- An authentication system.
  179. * :mod:`django.contrib.contenttypes` -- A framework for content types.
  180. * :mod:`django.contrib.sessions` -- A session framework.
  181. * :mod:`django.contrib.sites` -- A framework for managing multiple sites
  182. with one Django installation.
  183. * :mod:`django.contrib.messages` -- A messaging framework.
  184. * :mod:`django.contrib.staticfiles` -- A framework for managing
  185. static files.
  186. These applications are included by default as a convenience for the common case.
  187. Each of these applications makes use of at least one database table, though,
  188. so we need to create the tables in the database before we can use them. To do
  189. that, run the following command:
  190. .. code-block:: bash
  191. python manage.py syncdb
  192. The :djadmin:`syncdb` command looks at the :setting:`INSTALLED_APPS` setting and
  193. creates any necessary database tables according to the database settings in your
  194. :file:`settings.py` file. You'll see a message for each database table it
  195. creates, and you'll get a prompt asking you if you'd like to create a superuser
  196. account 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.
  200. .. admonition:: For the minimalists
  201. Like we said above, the default applications are included for the common
  202. case, but not everybody needs them. If you don't need any or all of them,
  203. feel free to comment-out or delete the appropriate line(s) from
  204. :setting:`INSTALLED_APPS` before running :djadmin:`syncdb`. The
  205. :djadmin:`syncdb` command will only create tables for apps in
  206. :setting:`INSTALLED_APPS`.
  207. .. _creating-models:
  208. Creating models
  209. ===============
  210. Now that your environment -- a "project" -- is set up, you're set to start
  211. doing work.
  212. Each application you write in Django consists of a Python package, somewhere
  213. on your `Python path`_, that follows a certain convention. Django comes with a
  214. utility that automatically generates the basic directory structure of an app,
  215. so you can focus on writing code rather than creating directories.
  216. .. admonition:: Projects vs. apps
  217. What's the difference between a project and an app? An app is a Web
  218. application that does something -- e.g., a Weblog system, a database of
  219. public records or a simple poll app. A project is a collection of
  220. configuration and apps for a particular Web site. A project can contain
  221. multiple apps. An app can be in multiple projects.
  222. Your apps can live anywhere on your `Python path`_. In this tutorial, we'll
  223. create our poll app right next to your :file:`manage.py` file so that it can be
  224. imported as its own top-level module, rather than a submodule of ``mysite``.
  225. To create your app, make sure you're in the same directory as :file:`manage.py`
  226. and type this command:
  227. .. code-block:: bash
  228. python manage.py startapp polls
  229. That'll create a directory :file:`polls`, which is laid out like this::
  230. polls/
  231. __init__.py
  232. models.py
  233. tests.py
  234. views.py
  235. This directory structure will house the poll application.
  236. The first step in writing a database Web app in Django is to define your models
  237. -- essentially, your database layout, with additional metadata.
  238. .. admonition:: Philosophy
  239. A model is the single, definitive source of data about your data. It contains
  240. the essential fields and behaviors of the data you're storing. Django follows
  241. the :ref:`DRY Principle <dry>`. The goal is to define your data model in one
  242. place and automatically derive things from it.
  243. In our simple poll app, we'll create two models: polls and choices. A poll has
  244. a question and a publication date. A choice has two fields: the text of the
  245. choice and a vote tally. Each choice is associated with a poll.
  246. These concepts are represented by simple Python classes. Edit the
  247. :file:`polls/models.py` file so it looks like this::
  248. from django.db import models
  249. class Poll(models.Model):
  250. question = models.CharField(max_length=200)
  251. pub_date = models.DateTimeField('date published')
  252. class Choice(models.Model):
  253. poll = models.ForeignKey(Poll)
  254. choice = models.CharField(max_length=200)
  255. votes = models.IntegerField()
  256. The code is straightforward. Each model is represented by a class that
  257. subclasses :class:`django.db.models.Model`. Each model has a number of class
  258. variables, each of which represents a database field in the model.
  259. Each field is represented by an instance of a :class:`~django.db.models.Field`
  260. class -- e.g., :class:`~django.db.models.CharField` for character fields and
  261. :class:`~django.db.models.DateTimeField` for datetimes. This tells Django what
  262. type of data each field holds.
  263. The name of each :class:`~django.db.models.Field` instance (e.g. ``question`` or
  264. ``pub_date`` ) is the field's name, in machine-friendly format. You'll use this
  265. value in your Python code, and your database will use it as the column name.
  266. You can use an optional first positional argument to a
  267. :class:`~django.db.models.Field` to designate a human-readable name. That's used
  268. in a couple of introspective parts of Django, and it doubles as documentation.
  269. If this field isn't provided, Django will use the machine-readable name. In this
  270. example, we've only defined a human-readable name for ``Poll.pub_date``. For all
  271. other fields in this model, the field's machine-readable name will suffice as
  272. its human-readable name.
  273. Some :class:`~django.db.models.Field` classes have required elements.
  274. :class:`~django.db.models.CharField`, for example, requires that you give it a
  275. :attr:`~django.db.models.Field.max_length`. That's used not only in the database
  276. schema, but in validation, as we'll soon see.
  277. Finally, note a relationship is defined, using
  278. :class:`~django.db.models.ForeignKey`. That tells Django each Choice is related
  279. to a single Poll. Django supports all the common database relationships:
  280. many-to-ones, many-to-manys and one-to-ones.
  281. .. _`Python path`: http://docs.python.org/tutorial/modules.html#the-module-search-path
  282. Activating models
  283. =================
  284. That small bit of model code gives Django a lot of information. With it, Django
  285. is able to:
  286. * Create a database schema (``CREATE TABLE`` statements) for this app.
  287. * Create a Python database-access API for accessing Poll and Choice objects.
  288. But first we need to tell our project that the ``polls`` app is installed.
  289. .. admonition:: Philosophy
  290. Django apps are "pluggable": You can use an app in multiple projects, and
  291. you can distribute apps, because they don't have to be tied to a given
  292. Django installation.
  293. Edit the :file:`settings.py` file again, and change the
  294. :setting:`INSTALLED_APPS` setting to include the string ``'polls'``. So
  295. it'll look like this::
  296. INSTALLED_APPS = (
  297. 'django.contrib.auth',
  298. 'django.contrib.contenttypes',
  299. 'django.contrib.sessions',
  300. 'django.contrib.sites',
  301. 'django.contrib.messages',
  302. 'django.contrib.staticfiles',
  303. # Uncomment the next line to enable the admin:
  304. # 'django.contrib.admin',
  305. # Uncomment the next line to enable admin documentation:
  306. # 'django.contrib.admindocs',
  307. 'polls',
  308. )
  309. Now Django knows to include the ``polls`` app. Let's run another
  310. command:
  311. .. code-block:: bash
  312. python manage.py sql polls
  313. You should see something similar to the following (the ``CREATE TABLE`` SQL
  314. statements for the polls app):
  315. .. code-block:: sql
  316. BEGIN;
  317. CREATE TABLE "polls_poll" (
  318. "id" serial NOT NULL PRIMARY KEY,
  319. "question" varchar(200) NOT NULL,
  320. "pub_date" timestamp with time zone NOT NULL
  321. );
  322. CREATE TABLE "polls_choice" (
  323. "id" serial NOT NULL PRIMARY KEY,
  324. "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id") DEFERRABLE INITIALLY DEFERRED,
  325. "choice" varchar(200) NOT NULL,
  326. "votes" integer NOT NULL
  327. );
  328. COMMIT;
  329. Note the following:
  330. * The exact output will vary depending on the database you are using.
  331. * Table names are automatically generated by combining the name of the app
  332. (``polls``) and the lowercase name of the model -- ``poll`` and
  333. ``choice``. (You can override this behavior.)
  334. * Primary keys (IDs) are added automatically. (You can override this, too.)
  335. * By convention, Django appends ``"_id"`` to the foreign key field name.
  336. (Yes, you can override this, as well.)
  337. * The foreign key relationship is made explicit by a ``REFERENCES``
  338. statement.
  339. * It's tailored to the database you're using, so database-specific field
  340. types such as ``auto_increment`` (MySQL), ``serial`` (PostgreSQL), or
  341. ``integer primary key`` (SQLite) are handled for you automatically. Same
  342. goes for quoting of field names -- e.g., using double quotes or single
  343. quotes. The author of this tutorial runs PostgreSQL, so the example
  344. output is in PostgreSQL syntax.
  345. * The :djadmin:`sql` command doesn't actually run the SQL in your database -
  346. it just prints it to the screen so that you can see what SQL Django thinks
  347. is required. If you wanted to, you could copy and paste this SQL into your
  348. database prompt. However, as we will see shortly, Django provides an
  349. easier way of committing the SQL to the database.
  350. If you're interested, also run the following commands:
  351. * :djadmin:`python manage.py validate <validate>` -- Checks for any errors
  352. in the construction of your models.
  353. * :djadmin:`python manage.py sqlcustom polls <sqlcustom>` -- Outputs any
  354. :ref:`custom SQL statements <initial-sql>` (such as table modifications or
  355. constraints) that are defined for the application.
  356. * :djadmin:`python manage.py sqlclear polls <sqlclear>` -- Outputs the
  357. necessary ``DROP TABLE`` statements for this app, according to which
  358. tables already exist in your database (if any).
  359. * :djadmin:`python manage.py sqlindexes polls <sqlindexes>` -- Outputs the
  360. ``CREATE INDEX`` statements for this app.
  361. * :djadmin:`python manage.py sqlall polls <sqlall>` -- A combination of all
  362. the SQL from the :djadmin:`sql`, :djadmin:`sqlcustom`, and
  363. :djadmin:`sqlindexes` commands.
  364. Looking at the output of those commands can help you understand what's actually
  365. happening under the hood.
  366. Now, run :djadmin:`syncdb` again to create those model tables in your database:
  367. .. code-block:: bash
  368. python manage.py syncdb
  369. The :djadmin:`syncdb` command runs the SQL from :djadmin:`sqlall` on your
  370. database for all apps in :setting:`INSTALLED_APPS` that don't already exist in
  371. your database. This creates all the tables, initial data and indexes for any
  372. apps you've added to your project since the last time you ran syncdb.
  373. :djadmin:`syncdb` can be called as often as you like, and it will only ever
  374. create the tables that don't exist.
  375. Read the :doc:`django-admin.py documentation </ref/django-admin>` for full
  376. information on what the ``manage.py`` utility can do.
  377. Playing with the API
  378. ====================
  379. Now, let's hop into the interactive Python shell and play around with the free
  380. API Django gives you. To invoke the Python shell, use this command:
  381. .. code-block:: bash
  382. python manage.py shell
  383. We're using this instead of simply typing "python", because :file:`manage.py`
  384. sets the ``DJANGO_SETTINGS_MODULE`` environment variable, which gives Django
  385. the Python import path to your :file:`settings.py` file.
  386. .. admonition:: Bypassing manage.py
  387. If you'd rather not use :file:`manage.py`, no problem. Just set the
  388. ``DJANGO_SETTINGS_MODULE`` environment variable to ``mysite.settings`` and
  389. run ``python`` from the same directory :file:`manage.py` is in (or ensure
  390. that directory is on the Python path, so that ``import mysite`` works).
  391. For more information on all of this, see the :doc:`django-admin.py
  392. documentation </ref/django-admin>`.
  393. Once you're in the shell, explore the :doc:`database API </topics/db/queries>`::
  394. >>> from polls.models import Poll, Choice # Import the model classes we just wrote.
  395. # No polls are in the system yet.
  396. >>> Poll.objects.all()
  397. []
  398. # Create a new Poll.
  399. # Support for time zones is enabled in the default settings file, so
  400. # Django expects a datetime with tzinfo for pub_date. Use timezone.now()
  401. # instead of datetime.datetime.now() and it will do the right thing.
  402. >>> from django.utils import timezone
  403. >>> p = Poll(question="What's new?", pub_date=timezone.now())
  404. # Save the object into the database. You have to call save() explicitly.
  405. >>> p.save()
  406. # Now it has an ID. Note that this might say "1L" instead of "1", depending
  407. # on which database you're using. That's no biggie; it just means your
  408. # database backend prefers to return integers as Python long integer
  409. # objects.
  410. >>> p.id
  411. 1
  412. # Access database columns via Python attributes.
  413. >>> p.question
  414. "What's new?"
  415. >>> p.pub_date
  416. datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
  417. # Change values by changing the attributes, then calling save().
  418. >>> p.question = "What's up?"
  419. >>> p.save()
  420. # objects.all() displays all the polls in the database.
  421. >>> Poll.objects.all()
  422. [<Poll: Poll object>]
  423. Wait a minute. ``<Poll: Poll object>`` is, utterly, an unhelpful representation
  424. of this object. Let's fix that by editing the polls model (in the
  425. ``polls/models.py`` file) and adding a
  426. :meth:`~django.db.models.Model.__unicode__` method to both ``Poll`` and
  427. ``Choice``::
  428. class Poll(models.Model):
  429. # ...
  430. def __unicode__(self):
  431. return self.question
  432. class Choice(models.Model):
  433. # ...
  434. def __unicode__(self):
  435. return self.choice
  436. It's important to add :meth:`~django.db.models.Model.__unicode__` methods to
  437. your models, not only for your own sanity when dealing with the interactive
  438. prompt, but also because objects' representations are used throughout Django's
  439. automatically-generated admin.
  440. .. admonition:: Why :meth:`~django.db.models.Model.__unicode__` and not
  441. :meth:`~django.db.models.Model.__str__`?
  442. If you're familiar with Python, you might be in the habit of adding
  443. :meth:`~django.db.models.Model.__str__` methods to your classes, not
  444. :meth:`~django.db.models.Model.__unicode__` methods. We use
  445. :meth:`~django.db.models.Model.__unicode__` here because Django models deal
  446. with Unicode by default. All data stored in your database is converted to
  447. Unicode when it's returned.
  448. Django models have a default :meth:`~django.db.models.Model.__str__` method
  449. that calls :meth:`~django.db.models.Model.__unicode__` and converts the
  450. result to a UTF-8 bytestring. This means that ``unicode(p)`` will return a
  451. Unicode string, and ``str(p)`` will return a normal string, with characters
  452. encoded as UTF-8.
  453. If all of this is gibberish to you, just remember to add
  454. :meth:`~django.db.models.Model.__unicode__` methods to your models. With any
  455. luck, things should Just Work for you.
  456. Note these are normal Python methods. Let's add a custom method, just for
  457. demonstration::
  458. import datetime
  459. from django.utils import timezone
  460. # ...
  461. class Poll(models.Model):
  462. # ...
  463. def was_published_recently(self):
  464. return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
  465. Note the addition of ``import datetime`` and ``from django.utils import
  466. timezone``, to reference Python's standard :mod:`datetime` module and Django's
  467. time-zone-related utilities in :mod:`django.utils.timezone`, respectively. If
  468. you aren't familiar with time zone handling in Python, you can learn more in
  469. the :doc:`time zone support docs </topics/i18n/timezones>`.
  470. Save these changes and start a new Python interactive shell by running
  471. ``python manage.py shell`` again::
  472. >>> from polls.models import Poll, Choice
  473. # Make sure our __unicode__() addition worked.
  474. >>> Poll.objects.all()
  475. [<Poll: What's up?>]
  476. # Django provides a rich database lookup API that's entirely driven by
  477. # keyword arguments.
  478. >>> Poll.objects.filter(id=1)
  479. [<Poll: What's up?>]
  480. >>> Poll.objects.filter(question__startswith='What')
  481. [<Poll: What's up?>]
  482. # Get the poll whose year is 2012.
  483. >>> Poll.objects.get(pub_date__year=2012)
  484. <Poll: What's up?>
  485. >>> Poll.objects.get(id=2)
  486. Traceback (most recent call last):
  487. ...
  488. DoesNotExist: Poll matching query does not exist.
  489. # Lookup by a primary key is the most common case, so Django provides a
  490. # shortcut for primary-key exact lookups.
  491. # The following is identical to Poll.objects.get(id=1).
  492. >>> Poll.objects.get(pk=1)
  493. <Poll: What's up?>
  494. # Make sure our custom method worked.
  495. >>> p = Poll.objects.get(pk=1)
  496. >>> p.was_published_recently()
  497. True
  498. # Give the Poll a couple of Choices. The create call constructs a new
  499. # choice object, does the INSERT statement, adds the choice to the set
  500. # of available choices and returns the new Choice object. Django creates
  501. # a set to hold the "other side" of a ForeignKey relation
  502. # (e.g. a poll's choices) which can be accessed via the API.
  503. >>> p = Poll.objects.get(pk=1)
  504. # Display any choices from the related object set -- none so far.
  505. >>> p.choice_set.all()
  506. []
  507. # Create three choices.
  508. >>> p.choice_set.create(choice='Not much', votes=0)
  509. <Choice: Not much>
  510. >>> p.choice_set.create(choice='The sky', votes=0)
  511. <Choice: The sky>
  512. >>> c = p.choice_set.create(choice='Just hacking again', votes=0)
  513. # Choice objects have API access to their related Poll objects.
  514. >>> c.poll
  515. <Poll: What's up?>
  516. # And vice versa: Poll objects get access to Choice objects.
  517. >>> p.choice_set.all()
  518. [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
  519. >>> p.choice_set.count()
  520. 3
  521. # The API automatically follows relationships as far as you need.
  522. # Use double underscores to separate relationships.
  523. # This works as many levels deep as you want; there's no limit.
  524. # Find all Choices for any poll whose pub_date is in 2012.
  525. >>> Choice.objects.filter(poll__pub_date__year=2012)
  526. [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
  527. # Let's delete one of the choices. Use delete() for that.
  528. >>> c = p.choice_set.filter(choice__startswith='Just hacking')
  529. >>> c.delete()
  530. For more information on model relations, see :doc:`Accessing related objects
  531. </ref/models/relations>`. For more on how to use double underscores to perform
  532. field lookups via the API, see :ref:`Field lookups <field-lookups-intro>`. For
  533. full details on the database API, see our :doc:`Database API reference
  534. </topics/db/queries>`.
  535. When you're comfortable with the API, read :doc:`part 2 of this tutorial
  536. </intro/tutorial02>` to get Django's automatic admin working.