2
0

overview.txt 13 KB

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