Debian Codegraph @

docs/intro/tutorial01.txt

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