tutorial01.txt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. in a shell prompt (indicated by the $ prefix):
  13. .. console::
  14. $ python -m django --version
  15. If Django is installed, you should see the version of your installation. If it
  16. isn't, you'll get an error telling "No module named django".
  17. This tutorial is written for Django |version|, which supports Python 3.6 and
  18. later. If the Django version doesn't match, you can refer to the tutorial for
  19. your version of Django by using the version switcher at the bottom right corner
  20. of this page, or update Django to the newest version. If you're using an older
  21. version of Python, check :ref:`faq-python-version-support` to find a compatible
  22. version of Django.
  23. See :doc:`How to install Django </topics/install>` for advice on how to remove
  24. older versions of Django and install a newer one.
  25. .. admonition:: Where to get help:
  26. If you're having trouble going through this tutorial, please post a message
  27. to |django-users| or drop by `#django on irc.freenode.net
  28. <irc://irc.freenode.net/django>`_ to chat with other Django users who might
  29. be able to help.
  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. .. console::
  40. $ django-admin startproject mysite
  41. This will create a ``mysite`` directory in your current directory. If it didn't
  42. work, see :ref:`troubleshooting-django-admin`.
  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. asgi.py
  65. wsgi.py
  66. These files are:
  67. * The outer :file:`mysite/` root directory is a container for your project. Its
  68. name doesn't matter to Django; you can rename it to anything you like.
  69. * :file:`manage.py`: A command-line utility that lets you interact with this
  70. Django project in various ways. You can read all the details about
  71. :file:`manage.py` in :doc:`/ref/django-admin`.
  72. * The inner :file:`mysite/` directory is the actual Python package for your
  73. project. Its name is the Python package name you'll need to use to import
  74. anything inside it (e.g. ``mysite.urls``).
  75. * :file:`mysite/__init__.py`: An empty file that tells Python that this
  76. directory should be considered a Python package. If you're a Python beginner,
  77. read :ref:`more about packages <tut-packages>` in the official Python docs.
  78. * :file:`mysite/settings.py`: Settings/configuration for this Django
  79. project. :doc:`/topics/settings` will tell you all about how settings
  80. work.
  81. * :file:`mysite/urls.py`: The URL declarations for this Django project; a
  82. "table of contents" of your Django-powered site. You can read more about
  83. URLs in :doc:`/topics/http/urls`.
  84. * :file:`mysite/asgi.py`: An entry-point for ASGI-compatible web servers to
  85. serve your project. See :doc:`/howto/deployment/asgi/index` for more details.
  86. * :file:`mysite/wsgi.py`: An entry-point for WSGI-compatible web servers to
  87. serve your project. See :doc:`/howto/deployment/wsgi/index` for more details.
  88. The development server
  89. ======================
  90. Let's verify your Django project works. Change into the outer :file:`mysite` directory, if
  91. you haven't already, and run the following commands:
  92. .. console::
  93. $ python manage.py runserver
  94. You'll see the following output on the command line:
  95. .. parsed-literal::
  96. Performing system checks...
  97. System check identified no issues (0 silenced).
  98. You have unapplied migrations; your app may not work properly until they are applied.
  99. Run 'python manage.py migrate' to apply them.
  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. .. note::
  105. Ignore the warning about unapplied database migrations for now; we'll deal
  106. with the database shortly.
  107. You've started the Django development server, a lightweight Web server written
  108. purely in Python. We've included this with Django so you can develop things
  109. rapidly, without having to deal with configuring a production server -- such as
  110. Apache -- until you're ready for production.
  111. Now's a good time to note: **don't** use this server in anything resembling a
  112. production environment. It's intended only for use while developing. (We're in
  113. the business of making Web frameworks, not Web servers.)
  114. Now that the server's running, visit http://127.0.0.1:8000/ with your Web
  115. browser. You'll see a "Congratulations!" page, with a rocket taking off.
  116. It worked!
  117. .. admonition:: Changing the port
  118. By default, the :djadmin:`runserver` command starts the development server
  119. on the internal IP at port 8000.
  120. If you want to change the server's port, pass
  121. it as a command-line argument. For instance, this command starts the server
  122. on port 8080:
  123. .. console::
  124. $ python manage.py runserver 8080
  125. If you want to change the server's IP, pass it along with the port. For
  126. example, to listen on all available public IPs (which is useful if you are
  127. running Vagrant or want to show off your work on other computers on the
  128. network), use:
  129. .. console::
  130. $ python manage.py runserver 0:8000
  131. **0** is a shortcut for **0.0.0.0**. Full docs for the development server
  132. can be found in the :djadmin:`runserver` reference.
  133. .. admonition:: Automatic reloading of :djadmin:`runserver`
  134. The development server automatically reloads Python code for each request
  135. as needed. You don't need to restart the server for code changes to take
  136. effect. However, some actions like adding files don't trigger a restart,
  137. so you'll have to restart the server in these cases.
  138. Creating the Polls app
  139. ======================
  140. Now that your environment -- a "project" -- is set up, you're set to start
  141. doing work.
  142. Each application you write in Django consists of a Python package that follows
  143. a certain convention. Django comes with a utility that automatically generates
  144. the basic directory structure of an app, so you can focus on writing code
  145. rather than creating directories.
  146. .. admonition:: Projects vs. apps
  147. What's the difference between a project and an app? An app is a Web
  148. application that does something -- e.g., a Weblog system, a database of
  149. public records or a small poll app. A project is a collection of
  150. configuration and apps for a particular website. A project can contain
  151. multiple apps. An app can be in multiple projects.
  152. Your apps can live anywhere on your :ref:`Python path <tut-searchpath>`. In
  153. this tutorial, we'll create our poll app right next to your :file:`manage.py`
  154. file so that it can be imported as its own top-level module, rather than a
  155. submodule of ``mysite``.
  156. To create your app, make sure you're in the same directory as :file:`manage.py`
  157. and type this command:
  158. .. console::
  159. $ python manage.py startapp polls
  160. That'll create a directory :file:`polls`, which is laid out like this::
  161. polls/
  162. __init__.py
  163. admin.py
  164. apps.py
  165. migrations/
  166. __init__.py
  167. models.py
  168. tests.py
  169. views.py
  170. This directory structure will house the poll application.
  171. Write your first view
  172. =====================
  173. Let's write the first view. Open the file ``polls/views.py``
  174. and put the following Python code in it:
  175. .. code-block:: python
  176. :caption: polls/views.py
  177. from django.http import HttpResponse
  178. def index(request):
  179. return HttpResponse("Hello, world. You're at the polls index.")
  180. This is the simplest view possible in Django. To call the view, we need to map
  181. it to a URL - and for this we need a URLconf.
  182. To create a URLconf in the polls directory, create a file called ``urls.py``.
  183. Your app directory should now look like::
  184. polls/
  185. __init__.py
  186. admin.py
  187. apps.py
  188. migrations/
  189. __init__.py
  190. models.py
  191. tests.py
  192. urls.py
  193. views.py
  194. In the ``polls/urls.py`` file include the following code:
  195. .. code-block:: python
  196. :caption: polls/urls.py
  197. from django.urls import path
  198. from . import views
  199. urlpatterns = [
  200. path('', views.index, name='index'),
  201. ]
  202. The next step is to point the root URLconf at the ``polls.urls`` module. In
  203. ``mysite/urls.py``, add an import for ``django.urls.include`` and insert an
  204. :func:`~django.urls.include` in the ``urlpatterns`` list, so you have:
  205. .. code-block:: python
  206. :caption: mysite/urls.py
  207. from django.contrib import admin
  208. from django.urls import include, path
  209. urlpatterns = [
  210. path('polls/', include('polls.urls')),
  211. path('admin/', admin.site.urls),
  212. ]
  213. The :func:`~django.urls.include` function allows referencing other URLconfs.
  214. Whenever Django encounters :func:`~django.urls.include`, it chops off whatever
  215. part of the URL matched up to that point and sends the remaining string to the
  216. included URLconf for further processing.
  217. The idea behind :func:`~django.urls.include` is to make it easy to
  218. plug-and-play URLs. Since polls are in their own URLconf
  219. (``polls/urls.py``), they can be placed under "/polls/", or under
  220. "/fun_polls/", or under "/content/polls/", or any other path root, and the
  221. app will still work.
  222. .. admonition:: When to use :func:`~django.urls.include()`
  223. You should always use ``include()`` when you include other URL patterns.
  224. ``admin.site.urls`` is the only exception to this.
  225. You have now wired an ``index`` view into the URLconf. Verify it's working with
  226. the following command:
  227. .. console::
  228. $ python manage.py runserver
  229. Go to http://localhost:8000/polls/ in your browser, and you should see the
  230. text "*Hello, world. You're at the polls index.*", which you defined in the
  231. ``index`` view.
  232. .. admonition:: Page not found?
  233. If you get an error page here, check that you're going to
  234. http://localhost:8000/polls/ and not http://localhost:8000/.
  235. The :func:`~django.urls.path` function is passed four arguments, two required:
  236. ``route`` and ``view``, and two optional: ``kwargs``, and ``name``.
  237. At this point, it's worth reviewing what these arguments are for.
  238. :func:`~django.urls.path` argument: ``route``
  239. ---------------------------------------------
  240. ``route`` is a string that contains a URL pattern. When processing a request,
  241. Django starts at the first pattern in ``urlpatterns`` and makes its way down
  242. the list, comparing the requested URL against each pattern until it finds one
  243. that matches.
  244. Patterns don't search GET and POST parameters, or the domain name. For example,
  245. in a request to ``https://www.example.com/myapp/``, the URLconf will look for
  246. ``myapp/``. In a request to ``https://www.example.com/myapp/?page=3``, the
  247. URLconf will also look for ``myapp/``.
  248. :func:`~django.urls.path` argument: ``view``
  249. --------------------------------------------
  250. When Django finds a matching pattern, it calls the specified view function with
  251. an :class:`~django.http.HttpRequest` object as the first argument and any
  252. "captured" values from the route as keyword arguments. We'll give an example
  253. of this in a bit.
  254. :func:`~django.urls.path` argument: ``kwargs``
  255. ----------------------------------------------
  256. Arbitrary keyword arguments can be passed in a dictionary to the target view. We
  257. aren't going to use this feature of Django in the tutorial.
  258. :func:`~django.urls.path` argument: ``name``
  259. --------------------------------------------
  260. Naming your URL lets you refer to it unambiguously from elsewhere in Django,
  261. especially from within templates. This powerful feature allows you to make
  262. global changes to the URL patterns of your project while only touching a single
  263. file.
  264. When you're comfortable with the basic request and response flow, read
  265. :doc:`part 2 of this tutorial </intro/tutorial02>` to start working with the
  266. database.