tutorial01.txt 28 KB

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