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