overview.txt 12 KB

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