tutorial01.txt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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:: console
  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.3 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
  27. <irc://irc.freenode.net/django>`_ to chat with other Django users who might
  28. be able to help.
  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:: console
  39. $ django-admin startproject mysite
  40. This will create a ``mysite`` directory in your current directory. If it didn't
  41. work, see :ref:`troubleshooting-django-admin`.
  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. These files are:
  65. * The outer :file:`mysite/` root directory is just a container for your
  66. project. Its name doesn't matter to Django; you can rename it to anything
  67. you like.
  68. * :file:`manage.py`: A command-line utility that lets you interact with this
  69. Django project in various ways. You can read all the details about
  70. :file:`manage.py` in :doc:`/ref/django-admin`.
  71. * The inner :file:`mysite/` directory is the actual Python package for your
  72. project. Its name is the Python package name you'll need to use to import
  73. anything inside it (e.g. ``mysite.urls``).
  74. * :file:`mysite/__init__.py`: An empty file that tells Python that this
  75. directory should be considered a Python package. (Read `more about
  76. packages`_ in the official Python docs if you're a Python beginner.)
  77. * :file:`mysite/settings.py`: Settings/configuration for this Django
  78. project. :doc:`/topics/settings` will tell you all about how settings
  79. work.
  80. * :file:`mysite/urls.py`: The URL declarations for this Django project; a
  81. "table of contents" of your Django-powered site. You can read more about
  82. URLs in :doc:`/topics/http/urls`.
  83. * :file:`mysite/wsgi.py`: An entry-point for WSGI-compatible web servers to
  84. serve your project. See :doc:`/howto/deployment/wsgi/index` for more details.
  85. .. _more about packages: https://docs.python.org/tutorial/modules.html#packages
  86. The development server
  87. ======================
  88. Let's verify your Django project works. Change into the outer :file:`mysite` directory, if
  89. you haven't already, and run the following commands:
  90. .. code-block:: console
  91. $ python manage.py runserver
  92. You'll see the following output on the command line:
  93. .. parsed-literal::
  94. Performing system checks...
  95. System check identified no issues (0 silenced).
  96. You have unapplied migrations; your app may not work properly until they are applied.
  97. Run 'python manage.py migrate' to apply them.
  98. |today| - 15:50:53
  99. Django version |version|, using settings 'mysite.settings'
  100. Starting development server at http://127.0.0.1:8000/
  101. Quit the server with CONTROL-C.
  102. .. note::
  103. Ignore the warning about unapplied database migrations for now; we'll deal
  104. with the database shortly.
  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:: console
  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 on your network), use:
  126. .. code-block:: console
  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. Creating the Polls app
  136. ======================
  137. Now that your environment -- a "project" -- is set up, you're set to start
  138. doing work.
  139. Each application you write in Django consists of a Python package that follows
  140. a certain convention. Django comes with a utility that automatically generates
  141. the basic directory structure of an app, so you can focus on writing code
  142. rather than creating directories.
  143. .. admonition:: Projects vs. apps
  144. What's the difference between a project and an app? An app is a Web
  145. application that does something -- e.g., a Weblog system, a database of
  146. public records or a simple poll app. A project is a collection of
  147. configuration and apps for a particular Web site. A project can contain
  148. multiple apps. An app can be in multiple projects.
  149. Your apps can live anywhere on your `Python path`_. In this tutorial, we'll
  150. create our poll app right next to your :file:`manage.py` file so that it can be
  151. imported as its own top-level module, rather than a submodule of ``mysite``.
  152. To create your app, make sure you're in the same directory as :file:`manage.py`
  153. and type this command:
  154. .. code-block:: console
  155. $ python manage.py startapp polls
  156. That'll create a directory :file:`polls`, which is laid out like this::
  157. polls/
  158. __init__.py
  159. admin.py
  160. migrations/
  161. __init__.py
  162. models.py
  163. tests.py
  164. views.py
  165. This directory structure will house the poll application.
  166. .. _`Python path`: https://docs.python.org/tutorial/modules.html#the-module-search-path
  167. Write your first view
  168. =====================
  169. Let's write the first view. Open the file ``polls/views.py``
  170. and put the following Python code in it:
  171. .. snippet::
  172. :filename: polls/views.py
  173. from django.http import HttpResponse
  174. def index(request):
  175. return HttpResponse("Hello, world. You're at the polls index.")
  176. This is the simplest view possible in Django. To call the view, we need to map
  177. it to a URL - and for this we need a URLconf.
  178. To create a URLconf in the polls directory, create a file called ``urls.py``.
  179. Your app directory should now look like::
  180. polls/
  181. __init__.py
  182. admin.py
  183. migrations/
  184. __init__.py
  185. models.py
  186. tests.py
  187. urls.py
  188. views.py
  189. In the ``polls/urls.py`` file include the following code:
  190. .. snippet::
  191. :filename: polls/urls.py
  192. from django.conf.urls import url
  193. from . import views
  194. urlpatterns = [
  195. url(r'^$', views.index, name='index'),
  196. ]
  197. The next step is to point the root URLconf at the ``polls.urls`` module. In
  198. ``mysite/urls.py`` insert an :func:`~django.conf.urls.include`, leaving you
  199. with:
  200. .. snippet::
  201. :filename: mysite/urls.py
  202. from django.conf.urls import include, url
  203. from django.contrib import admin
  204. urlpatterns = [
  205. url(r'^polls/', include('polls.urls')),
  206. url(r'^admin/', admin.site.urls),
  207. ]
  208. .. admonition:: Doesn't match what you see?
  209. If you're seeing ``include(admin.site.urls)`` instead of just
  210. ``admin.site.urls``, you're probably using a version of Django that
  211. doesn't match this tutorial version. You'll want to either switch to the
  212. older tutorial or the newer Django version.
  213. You have now wired an ``index`` view into the URLconf. Lets verify it's
  214. working, run the following command:
  215. .. code-block:: console
  216. $ python manage.py runserver
  217. Go to http://localhost:8000/polls/ in your browser, and you should see the
  218. text "*Hello, world. You're at the polls index.*", which you defined in the
  219. ``index`` view.
  220. The :func:`~django.conf.urls.url` function is passed four arguments, two
  221. required: ``regex`` and ``view``, and two optional: ``kwargs``, and ``name``.
  222. At this point, it's worth reviewing what these arguments are for.
  223. :func:`~django.conf.urls.url` argument: regex
  224. ---------------------------------------------
  225. The term "regex" is a commonly used short form meaning "regular expression",
  226. which is a syntax for matching patterns in strings, or in this case, url
  227. patterns. Django starts at the first regular expression and makes its way down
  228. the list, comparing the requested URL against each regular expression until it
  229. finds one that matches.
  230. Note that these regular expressions do not search GET and POST parameters, or
  231. the domain name. For example, in a request to
  232. ``http://www.example.com/myapp/``, the URLconf will look for ``myapp/``. In a
  233. request to ``http://www.example.com/myapp/?page=3``, the URLconf will also
  234. look for ``myapp/``.
  235. If you need help with regular expressions, see `Wikipedia's entry`_ and the
  236. documentation of the :mod:`re` module. Also, the O'Reilly book "Mastering
  237. Regular Expressions" by Jeffrey Friedl is fantastic. In practice, however,
  238. you don't need to be an expert on regular expressions, as you really only need
  239. to know how to capture simple patterns. In fact, complex regexes can have poor
  240. lookup performance, so you probably shouldn't rely on the full power of regexes.
  241. Finally, a performance note: these regular expressions are compiled the first
  242. time the URLconf module is loaded. They're super fast (as long as the lookups
  243. aren't too complex as noted above).
  244. .. _Wikipedia's entry: http://en.wikipedia.org/wiki/Regular_expression
  245. :func:`~django.conf.urls.url` argument: view
  246. --------------------------------------------
  247. When Django finds a regular expression match, Django calls the specified view
  248. function, with an :class:`~django.http.HttpRequest` object as the first
  249. argument and any “captured” values from the regular expression as other
  250. arguments. If the regex uses simple captures, values are passed as positional
  251. arguments; if it uses named captures, values are passed as keyword arguments.
  252. We'll give an example of this in a bit.
  253. :func:`~django.conf.urls.url` argument: kwargs
  254. ----------------------------------------------
  255. Arbitrary keyword arguments can be passed in a dictionary to the target view. We
  256. aren't going to use this feature of Django in the tutorial.
  257. :func:`~django.conf.urls.url` argument: name
  258. ---------------------------------------------
  259. Naming your URL lets you refer to it unambiguously from elsewhere in Django
  260. especially templates. This powerful feature allows you to make global changes
  261. to the url patterns of your project while only touching a single file.
  262. When you're comfortable with the basic request and response flow, read
  263. :doc:`part 2 of this tutorial </intro/tutorial02>` to start working with the
  264. database.