Debian Codegraph @

docs/intro/overview.txt

raw
1 ==================
2 Django at a glance
3 ==================
4
5 Because Django was developed in a fast-paced newsroom environment, it was
6 designed to make common web development tasks fast and easy. Here's an informal
7 overview of how to write a database-driven web app with Django.
8
9 The goal of this document is to give you enough technical specifics to
10 understand how Django works, but this isn't intended to be a tutorial or
11 reference -- but we've got both! When you're ready to start a project, you can
12 :doc:`start with the tutorial </intro/tutorial01>` or :doc:`dive right into more
13 detailed documentation </topics/index>`.
14
15 Design your model
16 =================
17
18 Although you can use Django without a database, it comes with an
19 `object-relational mapper`_ in which you describe your database layout in Python
20 code.
21
22 .. _object-relational mapper: https://en.wikipedia.org/wiki/Object-relational_mapping
23
24 The :doc:`data-model syntax </topics/db/models>` offers many rich ways of
25 representing your models -- so far, it's been solving many years' worth of
26 database-schema problems. Here's a quick example:
27
28 .. code-block:: python
29 :caption: ``news/models.py``
30
31 from django.db import models
32
33
34 class Reporter(models.Model):
35 full_name = models.CharField(max_length=70)
36
37 def __str__(self):
38 return self.full_name
39
40
41 class Article(models.Model):
42 pub_date = models.DateField()
43 headline = models.CharField(max_length=200)
44 content = models.TextField()
45 reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
46
47 def __str__(self):
48 return self.headline
49
50 Install it
51 ==========
52
53 Next, run the Django command-line utilities to create the database tables
54 automatically:
55
56 .. console::
57
58 $ python manage.py makemigrations
59 $ python manage.py migrate
60
61 The :djadmin:`makemigrations` command looks at all your available models and
62 creates migrations for whichever tables don't already exist. :djadmin:`migrate`
63 runs the migrations and creates tables in your database, as well as optionally
64 providing :doc:`much richer schema control </topics/migrations>`.
65
66 Enjoy the free API
67 ==================
68
69 With that, you've got a free, and rich, :doc:`Python API </topics/db/queries>`
70 to access your data. The API is created on the fly, no code generation
71 necessary:
72
73 .. code-block:: pycon
74
75 # Import the models we created from our "news" app
76 >>> from news.models import Article, Reporter
77
78 # No reporters are in the system yet.
79 >>> Reporter.objects.all()
80 <QuerySet []>
81
82 # Create a new Reporter.
83 >>> r = Reporter(full_name="John Smith")
84
85 # Save the object into the database. You have to call save() explicitly.
86 >>> r.save()
87
88 # Now it has an ID.
89 >>> r.id
90 1
91
92 # Now the new reporter is in the database.
93 >>> Reporter.objects.all()
94 <QuerySet [<Reporter: John Smith>]>
95
96 # Fields are represented as attributes on the Python object.
97 >>> r.full_name
98 'John Smith'
99
100 # Django provides a rich database lookup API.
101 >>> Reporter.objects.get(id=1)
102 <Reporter: John Smith>
103 >>> Reporter.objects.get(full_name__startswith="John")
104 <Reporter: John Smith>
105 >>> Reporter.objects.get(full_name__contains="mith")
106 <Reporter: John Smith>
107 >>> Reporter.objects.get(id=2)
108 Traceback (most recent call last):
109 ...
110 DoesNotExist: Reporter matching query does not exist.
111
112 # Create an article.
113 >>> from datetime import date
114 >>> a = Article(
115 ... pub_date=date.today(), headline="Django is cool", content="Yeah.", reporter=r
116 ... )
117 >>> a.save()
118
119 # Now the article is in the database.
120 >>> Article.objects.all()
121 <QuerySet [<Article: Django is cool>]>
122
123 # Article objects get API access to related Reporter objects.
124 >>> r = a.reporter
125 >>> r.full_name
126 'John Smith'
127
128 # And vice versa: Reporter objects get API access to Article objects.
129 >>> r.article_set.all()
130 <QuerySet [<Article: Django is cool>]>
131
132 # The API follows relationships as far as you need, performing efficient
133 # JOINs for you behind the scenes.
134 # This finds all articles by a reporter whose name starts with "John".
135 >>> Article.objects.filter(reporter__full_name__startswith="John")
136 <QuerySet [<Article: Django is cool>]>
137
138 # Change an object by altering its attributes and calling save().
139 >>> r.full_name = "Billy Goat"
140 >>> r.save()
141
142 # Delete an object with delete().
143 >>> r.delete()
144
145 A dynamic admin interface: it's not just scaffolding -- it's the whole house
146 ============================================================================
147
148 Once your models are defined, Django can automatically create a professional,
149 production ready :doc:`administrative interface </ref/contrib/admin/index>` --
150 a website that lets authenticated users add, change and delete objects. The
151 only step required is to register your model in the admin site:
152
153 .. code-block:: python
154 :caption: ``news/models.py``
155
156 from django.db import models
157
158
159 class Article(models.Model):
160 pub_date = models.DateField()
161 headline = models.CharField(max_length=200)
162 content = models.TextField()
163 reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
164
165 .. code-block:: python
166 :caption: ``news/admin.py``
167
168 from django.contrib import admin
169
170 from . import models
171
172 admin.site.register(models.Article)
173
174 The philosophy here is that your site is edited by a staff, or a client, or
175 maybe just you -- and you don't want to have to deal with creating backend
176 interfaces only to manage content.
177
178 One typical workflow in creating Django apps is to create models and get the
179 admin sites up and running as fast as possible, so your staff (or clients) can
180 start populating data. Then, develop the way data is presented to the public.
181
182 Design your URLs
183 ================
184
185 A clean, elegant URL scheme is an important detail in a high-quality web
186 application. Django encourages beautiful URL design and doesn't put any cruft
187 in URLs, like ``.php`` or ``.asp``.
188
189 To design URLs for an app, you create a Python module called a :doc:`URLconf
190 </topics/http/urls>`. A table of contents for your app, it contains a mapping
191 between URL patterns and Python callback functions. URLconfs also serve to
192 decouple URLs from Python code.
193
194 Here's what a URLconf might look like for the ``Reporter``/``Article``
195 example above:
196
197 .. code-block:: python
198 :caption: ``news/urls.py``
199
200 from django.urls import path
201
202 from . import views
203
204 urlpatterns = [
205 path("articles/<int:year>/", views.year_archive),
206 path("articles/<int:year>/<int:month>/", views.month_archive),
207 path("articles/<int:year>/<int:month>/<int:pk>/", views.article_detail),
208 ]
209
210 The code above maps URL paths to Python callback functions ("views"). The path
211 strings use parameter tags to "capture" values from the URLs. When a user
212 requests a page, Django runs through each path, in order, and stops at the
213 first one that matches the requested URL. (If none of them matches, Django
214 calls a special-case 404 view.) This is blazingly fast, because the paths are
215 compiled into regular expressions at load time.
216
217 Once one of the URL patterns matches, Django calls the given view, which is a
218 Python function. Each view gets passed a request object -- which contains
219 request metadata -- and the values captured in the pattern.
220
221 For example, if a user requested the URL "/articles/2005/05/39323/", Django
222 would call the function ``news.views.article_detail(request,
223 year=2005, month=5, pk=39323)``.
224
225 Write your views
226 ================
227
228 Each view is responsible for doing one of two things: Returning an
229 :class:`~django.http.HttpResponse` object containing the content for the
230 requested page, or raising an exception such as :class:`~django.http.Http404`.
231 The rest is up to you.
232
233 Generally, a view retrieves data according to the parameters, loads a template
234 and renders the template with the retrieved data. Here's an example view for
235 ``year_archive`` from above:
236
237 .. code-block:: python
238 :caption: ``news/views.py``
239
240 from django.shortcuts import render
241
242 from .models import Article
243
244
245 def year_archive(request, year):
246 a_list = Article.objects.filter(pub_date__year=year)
247 context = {"year": year, "article_list": a_list}
248 return render(request, "news/year_archive.html", context)
249
250 This example uses Django's :doc:`template system </topics/templates>`, which has
251 several powerful features but strives to stay simple enough for non-programmers
252 to use.
253
254 Design your templates
255 =====================
256
257 The code above loads the ``news/year_archive.html`` template.
258
259 Django has a template search path, which allows you to minimize redundancy among
260 templates. In your Django settings, you specify a list of directories to check
261 for templates with :setting:`DIRS <TEMPLATES-DIRS>`. If a template doesn't exist
262 in the first directory, it checks the second, and so on.
263
264 Let's say the ``news/year_archive.html`` template was found. Here's what that
265 might look like:
266
267 .. code-block:: html+django
268 :caption: ``news/templates/news/year_archive.html``
269
270 {% extends "base.html" %}
271
272 {% block title %}Articles for {{ year }}{% endblock %}
273
274 {% block content %}
275 <h1>Articles for {{ year }}</h1>
276
277 {% for article in article_list %}
278 <p>{{ article.headline }}</p>
279 <p>By {{ article.reporter.full_name }}</p>
280 <p>Published {{ article.pub_date|date:"F j, Y" }}</p>
281 {% endfor %}
282 {% endblock %}
283
284 Variables are surrounded by double-curly braces. ``{{ article.headline }}``
285 means "Output the value of the article's headline attribute." But dots aren't
286 used only for attribute lookup. They also can do dictionary-key lookup, index
287 lookup and function calls.
288
289 Note ``{{ article.pub_date|date:"F j, Y" }}`` uses a Unix-style "pipe" (the "|"
290 character). This is called a template filter, and it's a way to filter the value
291 of a variable. In this case, the date filter formats a Python datetime object in
292 the given format (as found in PHP's date function).
293
294 You can chain together as many filters as you'd like. You can write :ref:`custom
295 template filters <howto-writing-custom-template-filters>`. You can write
296 :doc:`custom template tags </howto/custom-template-tags>`, which run custom
297 Python code behind the scenes.
298
299 Finally, Django uses the concept of "template inheritance". That's what the
300 ``{% extends "base.html" %}`` does. It means "First load the template called
301 'base', which has defined a bunch of blocks, and fill the blocks with the
302 following blocks." In short, that lets you dramatically cut down on redundancy
303 in templates: each template has to define only what's unique to that template.
304
305 Here's what the "base.html" template, including the use of :doc:`static files
306 </howto/static-files/index>`, might look like:
307
308 .. code-block:: html+django
309 :caption: ``templates/base.html``
310
311 {% load static %}
312 <html lang="en">
313 <head>
314 <title>{% block title %}{% endblock %}</title>
315 </head>
316 <body>
317 <img src="{% static 'images/sitelogo.png' %}" alt="Logo">
318 {% block content %}{% endblock %}
319 </body>
320 </html>
321
322 Simplistically, it defines the look-and-feel of the site (with the site's logo),
323 and provides "holes" for child templates to fill. This means that a site redesign
324 can be done by changing a single file -- the base template.
325
326 It also lets you create multiple versions of a site, with different base
327 templates, while reusing child templates. Django's creators have used this
328 technique to create strikingly different mobile versions of sites by only
329 creating a new base template.
330
331 Note that you don't have to use Django's template system if you prefer another
332 system. While Django's template system is particularly well-integrated with
333 Django's model layer, nothing forces you to use it. For that matter, you don't
334 have to use Django's database API, either. You can use another database
335 abstraction layer, you can read XML files, you can read files off disk, or
336 anything you want. Each piece of Django -- models, views, templates -- is
337 decoupled from the next.
338
339 This is just the surface
340 ========================
341
342 This has been only a quick overview of Django's functionality. Some more useful
343 features:
344
345 * A :doc:`caching framework </topics/cache>` that integrates with memcached
346 or other backends.
347
348 * A :doc:`syndication framework </ref/contrib/syndication>` that lets you
349 create RSS and Atom feeds by writing a small Python class.
350
351 * More attractive automatically-generated admin features -- this overview
352 barely scratched the surface.
353
354 The next steps are for you to `download Django`_, read :doc:`the tutorial
355 </intro/tutorial01>` and join `the community`_. Thanks for your interest!
356
357 .. _download Django: https://www.djangoproject.com/download/
358 .. _the community: https://www.djangoproject.com/community/