tutorial01.txt 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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.10 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 head over to
  27. the :doc:`Getting Help</faq/help>` section of the FAQ.
  28. Creating a project
  29. ==================
  30. If this is your first time using Django, you'll have to take care of some
  31. initial setup. Namely, you'll need to auto-generate some code that establishes a
  32. Django :term:`project` -- a collection of settings for an instance of Django,
  33. including database configuration, Django-specific options and
  34. application-specific settings.
  35. From the command line, ``cd`` into a directory where you'd like to store your
  36. code and create a new directory named ``djangotutorial``. (This directory name
  37. doesn't matter to Django; you can rename it to anything you like.)
  38. .. console::
  39. $ mkdir djangotutorial
  40. Then, run the following command to bootstrap a new Django project:
  41. .. console::
  42. $ django-admin startproject mysite djangotutorial
  43. This will create a project called ``mysite`` inside the ``djangotutorial``
  44. directory. If it didn't work, see :ref:`troubleshooting-django-admin`.
  45. .. note::
  46. You'll need to avoid naming projects after built-in Python or Django
  47. components. In particular, this means you should avoid using names like
  48. ``django`` (which will conflict with Django itself) or ``test`` (which
  49. conflicts with a built-in Python package).
  50. Let's look at what :djadmin:`startproject` created:
  51. .. code-block:: text
  52. djangotutorial/
  53. manage.py
  54. mysite/
  55. __init__.py
  56. settings.py
  57. urls.py
  58. asgi.py
  59. wsgi.py
  60. These files are:
  61. * :file:`manage.py`: A command-line utility that lets you interact with this
  62. Django project in various ways. You can read all the details about
  63. :file:`manage.py` in :doc:`/ref/django-admin`.
  64. * :file:`mysite/`: A directory that is the actual Python package for your
  65. project. Its name is the Python package name you'll need to use to import
  66. anything inside it (e.g. ``mysite.urls``).
  67. * :file:`mysite/__init__.py`: An empty file that tells Python that this
  68. directory should be considered a Python package. If you're a Python beginner,
  69. read :ref:`more about packages <tut-packages>` in the official Python docs.
  70. * :file:`mysite/settings.py`: Settings/configuration for this Django
  71. project. :doc:`/topics/settings` will tell you all about how settings
  72. work.
  73. * :file:`mysite/urls.py`: The URL declarations for this Django project; a
  74. "table of contents" of your Django-powered site. You can read more about
  75. URLs in :doc:`/topics/http/urls`.
  76. * :file:`mysite/asgi.py`: An entry-point for ASGI-compatible web servers to
  77. serve your project. See :doc:`/howto/deployment/asgi/index` for more details.
  78. * :file:`mysite/wsgi.py`: An entry-point for WSGI-compatible web servers to
  79. serve your project. See :doc:`/howto/deployment/wsgi/index` for more details.
  80. The development server
  81. ======================
  82. Let's verify your Django project works. Change into the :file:`djangotutorial`
  83. directory, if you haven't already, and run the following commands:
  84. .. console::
  85. $ python manage.py runserver
  86. You'll see the following output on the command line:
  87. .. parsed-literal::
  88. Performing system checks...
  89. System check identified no issues (0 silenced).
  90. You have unapplied migrations; your app may not work properly until they are applied.
  91. Run 'python manage.py migrate' to apply them.
  92. |today| - 15:50:53
  93. Django version |version|, using settings 'mysite.settings'
  94. Starting development server at http://127.0.0.1:8000/
  95. Quit the server with CONTROL-C.
  96. WARNING: This is a development server. Do not use it in a production setting. Use a production WSGI or ASGI server instead.
  97. For more information on production servers see: https://docs.djangoproject.com/en/|version|/howto/deployment/
  98. .. note::
  99. Ignore the warning about unapplied database migrations for now; we'll deal
  100. with the database shortly.
  101. Now that the server's running, visit http://127.0.0.1:8000/ with your web
  102. browser. You'll see a "Congratulations!" page, with a rocket taking off.
  103. It worked!
  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. (To serve the site on a different port, see the :djadmin:`runserver` reference.)
  112. .. admonition:: Automatic reloading of :djadmin:`runserver`
  113. The development server automatically reloads Python code for each request
  114. as needed. You don't need to restart the server for code changes to take
  115. effect. However, some actions like adding files don't trigger a restart,
  116. so you'll have to restart the server in these cases.
  117. Creating the Polls app
  118. ======================
  119. Now that your environment -- a "project" -- is set up, you're set to start
  120. doing work.
  121. Each application you write in Django consists of a Python package that follows
  122. a certain convention. Django comes with a utility that automatically generates
  123. the basic directory structure of an app, so you can focus on writing code
  124. rather than creating directories.
  125. .. admonition:: Projects vs. apps
  126. What's the difference between a project and an app? An app is a web
  127. application that does something -- e.g., a blog system, a database of
  128. public records or a small poll app. A project is a collection of
  129. configuration and apps for a particular website. A project can contain
  130. multiple apps. An app can be in multiple projects.
  131. Your apps can live anywhere in your :ref:`Python path <tut-searchpath>`. In
  132. this tutorial, we'll create our poll app inside the ``djangotutorial`` folder.
  133. To create your app, make sure you're in the same directory as :file:`manage.py`
  134. and type this command:
  135. .. console::
  136. $ python manage.py startapp polls
  137. That'll create a directory :file:`polls`, which is laid out like this:
  138. .. code-block:: text
  139. polls/
  140. __init__.py
  141. admin.py
  142. apps.py
  143. migrations/
  144. __init__.py
  145. models.py
  146. tests.py
  147. views.py
  148. This directory structure will house the poll application.
  149. Write your first view
  150. =====================
  151. Let's write the first view. Open the file ``polls/views.py``
  152. and put the following Python code in it:
  153. .. code-block:: python
  154. :caption: ``polls/views.py``
  155. from django.http import HttpResponse
  156. def index(request):
  157. return HttpResponse("Hello, world. You're at the polls index.")
  158. This is the most basic view possible in Django. To access it in a browser, we
  159. need to map it to a URL - and for this we need to define a URL configuration,
  160. or "URLconf" for short. These URL configurations are defined inside each
  161. Django app, and they are Python files named ``urls.py``.
  162. To define a URLconf for the ``polls`` app, create a file ``polls/urls.py``
  163. with the following content:
  164. .. code-block:: python
  165. :caption: ``polls/urls.py``
  166. from django.urls import path
  167. from . import views
  168. urlpatterns = [
  169. path("", views.index, name="index"),
  170. ]
  171. Your app directory should now look like:
  172. .. code-block:: text
  173. polls/
  174. __init__.py
  175. admin.py
  176. apps.py
  177. migrations/
  178. __init__.py
  179. models.py
  180. tests.py
  181. urls.py
  182. views.py
  183. The next step is to configure the root URLconf in the ``mysite`` project to
  184. include the URLconf defined in ``polls.urls``. To do this, add an import for
  185. ``django.urls.include`` in ``mysite/urls.py`` and insert an
  186. :func:`~django.urls.include` in the ``urlpatterns`` list, so you have:
  187. .. code-block:: python
  188. :caption: ``mysite/urls.py``
  189. from django.contrib import admin
  190. from django.urls import include, path
  191. urlpatterns = [
  192. path("polls/", include("polls.urls")),
  193. path("admin/", admin.site.urls),
  194. ]
  195. The :func:`~django.urls.path` function expects at least two arguments:
  196. ``route`` and ``view``.
  197. The :func:`~django.urls.include` function allows referencing other URLconfs.
  198. Whenever Django encounters :func:`~django.urls.include`, it chops off whatever
  199. part of the URL matched up to that point and sends the remaining string to the
  200. included URLconf for further processing.
  201. The idea behind :func:`~django.urls.include` is to make it easy to
  202. plug-and-play URLs. Since polls are in their own URLconf
  203. (``polls/urls.py``), they can be placed under "/polls/", or under
  204. "/fun_polls/", or under "/content/polls/", or any other path root, and the
  205. app will still work.
  206. .. admonition:: When to use :func:`~django.urls.include()`
  207. You should always use ``include()`` when you include other URL patterns.
  208. The only exception is ``admin.site.urls``, which is a pre-built URLconf
  209. provided by Django for the default admin site.
  210. You have now wired an ``index`` view into the URLconf. Verify it's working with
  211. the following command:
  212. .. console::
  213. $ python manage.py runserver
  214. Go to http://localhost:8000/polls/ in your browser, and you should see the
  215. text "*Hello, world. You're at the polls index.*", which you defined in the
  216. ``index`` view.
  217. .. admonition:: Page not found?
  218. If you get an error page here, check that you're going to
  219. http://localhost:8000/polls/ and not http://localhost:8000/.
  220. When you're comfortable with the basic request and response flow, read
  221. :doc:`part 2 of this tutorial </intro/tutorial02>` to start working with the
  222. database.