tutorial01.txt 31 KB

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