1. =====================================
    
  2. Writing your first Django app, part 1
    
  3. =====================================
    
  4. 
    
  5. Let's learn by example.
    
  6. 
    
  7. Throughout this tutorial, we'll walk you through the creation of a basic
    
  8. poll application.
    
  9. 
    
  10. It'll consist of two parts:
    
  11. 
    
  12. * A public site that lets people view polls and vote in them.
    
  13. * An admin site that lets you add, change, and delete polls.
    
  14. 
    
  15. We'll assume you have :doc:`Django installed </intro/install>` already. You can
    
  16. tell Django is installed and which version by running the following command
    
  17. in a shell prompt (indicated by the $ prefix):
    
  18. 
    
  19. .. console::
    
  20. 
    
  21.     $ python -m django --version
    
  22. 
    
  23. If Django is installed, you should see the version of your installation. If it
    
  24. isn't, you'll get an error telling "No module named django".
    
  25. 
    
  26. This tutorial is written for Django |version|, which supports Python 3.8 and
    
  27. later. If the Django version doesn't match, you can refer to the tutorial for
    
  28. your version of Django by using the version switcher at the bottom right corner
    
  29. of this page, or update Django to the newest version. If you're using an older
    
  30. version of Python, check :ref:`faq-python-version-support` to find a compatible
    
  31. version of Django.
    
  32. 
    
  33. See :doc:`How to install Django </topics/install>` for advice on how to remove
    
  34. older versions of Django and install a newer one.
    
  35. 
    
  36. .. admonition:: Where to get help:
    
  37. 
    
  38.     If you're having trouble going through this tutorial, please head over to
    
  39.     the :doc:`Getting Help</faq/help>` section of the FAQ.
    
  40. 
    
  41. Creating a project
    
  42. ==================
    
  43. 
    
  44. If this is your first time using Django, you'll have to take care of some
    
  45. initial setup. Namely, you'll need to auto-generate some code that establishes a
    
  46. Django :term:`project` -- a collection of settings for an instance of Django,
    
  47. including database configuration, Django-specific options and
    
  48. application-specific settings.
    
  49. 
    
  50. From the command line, ``cd`` into a directory where you'd like to store your
    
  51. code, then run the following command:
    
  52. 
    
  53. .. console::
    
  54. 
    
  55.    $ django-admin startproject mysite
    
  56. 
    
  57. This will create a ``mysite`` directory in your current directory. If it didn't
    
  58. work, see :ref:`troubleshooting-django-admin`.
    
  59. 
    
  60. .. note::
    
  61. 
    
  62.     You'll need to avoid naming projects after built-in Python or Django
    
  63.     components. In particular, this means you should avoid using names like
    
  64.     ``django`` (which will conflict with Django itself) or ``test`` (which
    
  65.     conflicts with a built-in Python package).
    
  66. 
    
  67. .. admonition:: Where should this code live?
    
  68. 
    
  69.     If your background is in plain old PHP (with no use of modern frameworks),
    
  70.     you're probably used to putting code under the web server's document root
    
  71.     (in a place such as ``/var/www``). With Django, you don't do that. It's
    
  72.     not a good idea to put any of this Python code within your web server's
    
  73.     document root, because it risks the possibility that people may be able
    
  74.     to view your code over the web. That's not good for security.
    
  75. 
    
  76.     Put your code in some directory **outside** of the document root, such as
    
  77.     :file:`/home/mycode`.
    
  78. 
    
  79. Let's look at what :djadmin:`startproject` created::
    
  80. 
    
  81.     mysite/
    
  82.         manage.py
    
  83.         mysite/
    
  84.             __init__.py
    
  85.             settings.py
    
  86.             urls.py
    
  87.             asgi.py
    
  88.             wsgi.py
    
  89. 
    
  90. These files are:
    
  91. 
    
  92. * The outer :file:`mysite/` root directory is a container for your project. Its
    
  93.   name doesn't matter to Django; you can rename it to anything you like.
    
  94. 
    
  95. * :file:`manage.py`: A command-line utility that lets you interact with this
    
  96.   Django project in various ways. You can read all the details about
    
  97.   :file:`manage.py` in :doc:`/ref/django-admin`.
    
  98. 
    
  99. * The inner :file:`mysite/` directory is the actual Python package for your
    
  100.   project. Its name is the Python package name you'll need to use to import
    
  101.   anything inside it (e.g. ``mysite.urls``).
    
  102. 
    
  103. * :file:`mysite/__init__.py`: An empty file that tells Python that this
    
  104.   directory should be considered a Python package. If you're a Python beginner,
    
  105.   read :ref:`more about packages <tut-packages>` in the official Python docs.
    
  106. 
    
  107. * :file:`mysite/settings.py`: Settings/configuration for this Django
    
  108.   project.  :doc:`/topics/settings` will tell you all about how settings
    
  109.   work.
    
  110. 
    
  111. * :file:`mysite/urls.py`: The URL declarations for this Django project; a
    
  112.   "table of contents" of your Django-powered site. You can read more about
    
  113.   URLs in :doc:`/topics/http/urls`.
    
  114. 
    
  115. * :file:`mysite/asgi.py`: An entry-point for ASGI-compatible web servers to
    
  116.   serve your project. See :doc:`/howto/deployment/asgi/index` for more details.
    
  117. 
    
  118. * :file:`mysite/wsgi.py`: An entry-point for WSGI-compatible web servers to
    
  119.   serve your project. See :doc:`/howto/deployment/wsgi/index` for more details.
    
  120. 
    
  121. The development server
    
  122. ======================
    
  123. 
    
  124. Let's verify your Django project works. Change into the outer :file:`mysite` directory, if
    
  125. you haven't already, and run the following commands:
    
  126. 
    
  127. .. console::
    
  128. 
    
  129.    $ python manage.py runserver
    
  130. 
    
  131. You'll see the following output on the command line:
    
  132. 
    
  133. .. parsed-literal::
    
  134. 
    
  135.     Performing system checks...
    
  136. 
    
  137.     System check identified no issues (0 silenced).
    
  138. 
    
  139.     You have unapplied migrations; your app may not work properly until they are applied.
    
  140.     Run 'python manage.py migrate' to apply them.
    
  141. 
    
  142.     |today| - 15:50:53
    
  143.     Django version |version|, using settings 'mysite.settings'
    
  144.     Starting development server at http://127.0.0.1:8000/
    
  145.     Quit the server with CONTROL-C.
    
  146. 
    
  147. .. note::
    
  148.     Ignore the warning about unapplied database migrations for now; we'll deal
    
  149.     with the database shortly.
    
  150. 
    
  151. You've started the Django development server, a lightweight web server written
    
  152. purely in Python. We've included this with Django so you can develop things
    
  153. rapidly, without having to deal with configuring a production server -- such as
    
  154. Apache -- until you're ready for production.
    
  155. 
    
  156. Now's a good time to note: **don't** use this server in anything resembling a
    
  157. production environment. It's intended only for use while developing. (We're in
    
  158. the business of making web frameworks, not web servers.)
    
  159. 
    
  160. Now that the server's running, visit http://127.0.0.1:8000/ with your web
    
  161. browser. You'll see a "Congratulations!" page, with a rocket taking off.
    
  162. It worked!
    
  163. 
    
  164. .. admonition:: Changing the port
    
  165. 
    
  166.     By default, the :djadmin:`runserver` command starts the development server
    
  167.     on the internal IP at port 8000.
    
  168. 
    
  169.     If you want to change the server's port, pass
    
  170.     it as a command-line argument. For instance, this command starts the server
    
  171.     on port 8080:
    
  172. 
    
  173.     .. console::
    
  174. 
    
  175.         $ python manage.py runserver 8080
    
  176. 
    
  177.     If you want to change the server's IP, pass it along with the port. For
    
  178.     example, to listen on all available public IPs (which is useful if you are
    
  179.     running Vagrant or want to show off your work on other computers on the
    
  180.     network), use:
    
  181. 
    
  182.     .. console::
    
  183. 
    
  184.         $ python manage.py runserver 0.0.0.0:8000
    
  185. 
    
  186.     Full docs for the development server can be found in the
    
  187.     :djadmin:`runserver` reference.
    
  188. 
    
  189. .. admonition:: Automatic reloading of :djadmin:`runserver`
    
  190. 
    
  191.     The development server automatically reloads Python code for each request
    
  192.     as needed. You don't need to restart the server for code changes to take
    
  193.     effect. However, some actions like adding files don't trigger a restart,
    
  194.     so you'll have to restart the server in these cases.
    
  195. 
    
  196. Creating the Polls app
    
  197. ======================
    
  198. 
    
  199. Now that your environment -- a "project" -- is set up, you're set to start
    
  200. doing work.
    
  201. 
    
  202. Each application you write in Django consists of a Python package that follows
    
  203. a certain convention. Django comes with a utility that automatically generates
    
  204. the basic directory structure of an app, so you can focus on writing code
    
  205. rather than creating directories.
    
  206. 
    
  207. .. admonition:: Projects vs. apps
    
  208. 
    
  209.     What's the difference between a project and an app? An app is a web
    
  210.     application that does something -- e.g., a blog system, a database of
    
  211.     public records or a small poll app. A project is a collection of
    
  212.     configuration and apps for a particular website. A project can contain
    
  213.     multiple apps. An app can be in multiple projects.
    
  214. 
    
  215. Your apps can live anywhere on your :ref:`Python path <tut-searchpath>`. In
    
  216. this tutorial, we'll create our poll app in the same directory as your
    
  217. :file:`manage.py` file so that it can be imported as its own top-level module,
    
  218. rather than a submodule of ``mysite``.
    
  219. 
    
  220. To create your app, make sure you're in the same directory as :file:`manage.py`
    
  221. and type this command:
    
  222. 
    
  223. .. console::
    
  224. 
    
  225.     $ python manage.py startapp polls
    
  226. 
    
  227. That'll create a directory :file:`polls`, which is laid out like this::
    
  228. 
    
  229.     polls/
    
  230.         __init__.py
    
  231.         admin.py
    
  232.         apps.py
    
  233.         migrations/
    
  234.             __init__.py
    
  235.         models.py
    
  236.         tests.py
    
  237.         views.py
    
  238. 
    
  239. This directory structure will house the poll application.
    
  240. 
    
  241. Write your first view
    
  242. =====================
    
  243. 
    
  244. Let's write the first view. Open the file ``polls/views.py``
    
  245. and put the following Python code in it:
    
  246. 
    
  247. .. code-block:: python
    
  248.     :caption: ``polls/views.py``
    
  249. 
    
  250.     from django.http import HttpResponse
    
  251. 
    
  252. 
    
  253.     def index(request):
    
  254.         return HttpResponse("Hello, world. You're at the polls index.")
    
  255. 
    
  256. This is the simplest view possible in Django. To call the view, we need to map
    
  257. it to a URL - and for this we need a URLconf.
    
  258. 
    
  259. To create a URLconf in the polls directory, create a file called ``urls.py``.
    
  260. Your app directory should now look like::
    
  261. 
    
  262.     polls/
    
  263.         __init__.py
    
  264.         admin.py
    
  265.         apps.py
    
  266.         migrations/
    
  267.             __init__.py
    
  268.         models.py
    
  269.         tests.py
    
  270.         urls.py
    
  271.         views.py
    
  272. 
    
  273. In the ``polls/urls.py`` file include the following code:
    
  274. 
    
  275. .. code-block:: python
    
  276.     :caption: ``polls/urls.py``
    
  277. 
    
  278.     from django.urls import path
    
  279. 
    
  280.     from . import views
    
  281. 
    
  282.     urlpatterns = [
    
  283.         path('', views.index, name='index'),
    
  284.     ]
    
  285. 
    
  286. The next step is to point the root URLconf at the ``polls.urls`` module. In
    
  287. ``mysite/urls.py``, add an import for ``django.urls.include`` and insert an
    
  288. :func:`~django.urls.include` in the ``urlpatterns`` list, so you have:
    
  289. 
    
  290. .. code-block:: python
    
  291.     :caption: ``mysite/urls.py``
    
  292. 
    
  293.     from django.contrib import admin
    
  294.     from django.urls import include, path
    
  295. 
    
  296.     urlpatterns = [
    
  297.         path('polls/', include('polls.urls')),
    
  298.         path('admin/', admin.site.urls),
    
  299.     ]
    
  300. 
    
  301. The :func:`~django.urls.include` function allows referencing other URLconfs.
    
  302. Whenever Django encounters :func:`~django.urls.include`, it chops off whatever
    
  303. part of the URL matched up to that point and sends the remaining string to the
    
  304. included URLconf for further processing.
    
  305. 
    
  306. The idea behind :func:`~django.urls.include` is to make it easy to
    
  307. plug-and-play URLs. Since polls are in their own URLconf
    
  308. (``polls/urls.py``), they can be placed under "/polls/", or under
    
  309. "/fun_polls/", or under "/content/polls/", or any other path root, and the
    
  310. app will still work.
    
  311. 
    
  312. .. admonition:: When to use :func:`~django.urls.include()`
    
  313. 
    
  314.     You should always use ``include()`` when you include other URL patterns.
    
  315.     ``admin.site.urls`` is the only exception to this.
    
  316. 
    
  317. You have now wired an ``index`` view into the URLconf. Verify it's working with
    
  318. the following command:
    
  319. 
    
  320. .. console::
    
  321. 
    
  322.    $ python manage.py runserver
    
  323. 
    
  324. Go to http://localhost:8000/polls/ in your browser, and you should see the
    
  325. text "*Hello, world. You're at the polls index.*", which you defined in the
    
  326. ``index`` view.
    
  327. 
    
  328. .. admonition:: Page not found?
    
  329. 
    
  330.     If you get an error page here, check that you're going to
    
  331.     http://localhost:8000/polls/ and not http://localhost:8000/.
    
  332. 
    
  333. The :func:`~django.urls.path` function is passed four arguments, two required:
    
  334. ``route`` and ``view``, and two optional: ``kwargs``, and ``name``.
    
  335. At this point, it's worth reviewing what these arguments are for.
    
  336. 
    
  337. :func:`~django.urls.path` argument: ``route``
    
  338. ---------------------------------------------
    
  339. 
    
  340. ``route`` is a string that contains a URL pattern. When processing a request,
    
  341. Django starts at the first pattern in ``urlpatterns`` and makes its way down
    
  342. the list, comparing the requested URL against each pattern until it finds one
    
  343. that matches.
    
  344. 
    
  345. Patterns don't search GET and POST parameters, or the domain name. For example,
    
  346. in a request to ``https://www.example.com/myapp/``, the URLconf will look for
    
  347. ``myapp/``. In a request to ``https://www.example.com/myapp/?page=3``, the
    
  348. URLconf will also look for ``myapp/``.
    
  349. 
    
  350. :func:`~django.urls.path` argument: ``view``
    
  351. --------------------------------------------
    
  352. 
    
  353. When Django finds a matching pattern, it calls the specified view function with
    
  354. an :class:`~django.http.HttpRequest` object as the first argument and any
    
  355. "captured" values from the route as keyword arguments. We'll give an example
    
  356. of this in a bit.
    
  357. 
    
  358. :func:`~django.urls.path` argument: ``kwargs``
    
  359. ----------------------------------------------
    
  360. 
    
  361. Arbitrary keyword arguments can be passed in a dictionary to the target view. We
    
  362. aren't going to use this feature of Django in the tutorial.
    
  363. 
    
  364. :func:`~django.urls.path` argument: ``name``
    
  365. --------------------------------------------
    
  366. 
    
  367. Naming your URL lets you refer to it unambiguously from elsewhere in Django,
    
  368. especially from within templates. This powerful feature allows you to make
    
  369. global changes to the URL patterns of your project while only touching a single
    
  370. file.
    
  371. 
    
  372. When you're comfortable with the basic request and response flow, read
    
  373. :doc:`part 2 of this tutorial </intro/tutorial02>` to start working with the
    
  374. database.