overview.txt 12 KB

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